Bash 数组不接受通配符
Bash Array not accepting WildCard
我有一个在 bash 脚本中设置的数组。我的目标是通过具有许多网络接口的服务器上的特定端口执行 ping 操作。例如 ping -I eth3 172.26.0.1 命令强制 ping 通过 eth3
当我设置一个 bash 数组时,如果我单独调用元素(端口),我可以让代码工作。例如这里我告诉它 ping Element 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 ping
[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/
编辑 - 我不确定为什么我在这个问题上被否决了。请指教
-I
选项只占用一个接口;你需要遍历数组:
for ifc in "${ethernet[@]}"; do
ping -c 1 -I "$ifc" 172.26.0.1
done
使用 xargs:
printf "%s\n" "${ethernet[@]}" | xargs -I {} ping -c 1 -I {} 172.26.0.1
我有一个在 bash 脚本中设置的数组。我的目标是通过具有许多网络接口的服务器上的特定端口执行 ping 操作。例如 ping -I eth3 172.26.0.1 命令强制 ping 通过 eth3
当我设置一个 bash 数组时,如果我单独调用元素(端口),我可以让代码工作。例如这里我告诉它 ping Element 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 ping
[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/
编辑 - 我不确定为什么我在这个问题上被否决了。请指教
-I
选项只占用一个接口;你需要遍历数组:
for ifc in "${ethernet[@]}"; do
ping -c 1 -I "$ifc" 172.26.0.1
done
使用 xargs:
printf "%s\n" "${ethernet[@]}" | xargs -I {} ping -c 1 -I {} 172.26.0.1