我有一個數組,我已在bash腳本中設置。我的目標是通過具有多個網絡接口的服務器上的特定端口進行ping。例如ping -I eth3 172.26.0.1命令強制通過eth3 ping命令Bash數組不接受通配符
當我設置一個bash數組時,如果我單獨調用元素(端口),我可以使代碼工作。比如在這裏我告訴它平元2或eth5
ethernet[0]='eth3'
ethernet[1]='eth4'
ethernet[2]='eth5'
ethernet[3]='eth6'
ping -c 1 -I ${ethernet[2]} 172.26.0.1
該腳本和坪通過ETH2
[13:49:35] shock:/dumps # bash -x ARRAY
+ ethernet[0]=eth3
+ ethernet[1]=eth4
+ ethernet[2]=eth5
+ ethernet[3]=eth6
+ ping -c 1 -I eth5 172.26.0.1
PING 172.26.0.1 (172.26.0.1) from 172.26.0.192 eth5: 56(84) bytes of data.
From 172.26.0.192 icmp_seq=1 Destination Host Unreachable
--- 172.26.0.1 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 3001ms
但是如果我使用通配符而不只是元件2它死的第二個元素上(Eth4)
ethernet[0]='eth3'
ethernet[1]='eth4'
ethernet[2]='eth5'
ethernet[3]='eth6'
ping -c 1 -I ${ethernet[*]} 172.26.0.1
[13:48:12] shock:/dumps # bash -x ARRAY
+ ethernet[0]=eth3
+ ethernet[1]=eth4
+ ethernet[2]=eth5
+ ethernet[3]=eth6
+ ping -c 1 -I eth3 eth4 eth5 eth6 172.26.0.1
ping: unknown host eth4
任何想法,至於爲什麼通配符在陣列中的第二個元素上死亡?我不熟悉腳本編寫,我只是嘗試使用從本文中學到的知識並將其應用於有用的網絡腳本。由於
http://www.thegeekstuff.com/2010/06/bash-array-tutorial/
編輯 - 我不知道爲什麼我被否決了這個這個問題。請指教
正在創建是錯誤的ping命令。您需要爲每個接口發出單獨的ping命令。 – stark
當您看到'eth3 eth4 eth5 eth6'時''{ethernet [*]}'擴展到所有數組元素。在$ {ethernet [*]}中使用'for'循環來解決這個問題。做ping -c 1 -I $ i 172.26.0.1;完成' –
@NarūnasK引用可變擴展。特別是使用'[@]'進行數組擴展以保證它們對於具有空格的值是安全的。 –