我有这样的剧本:
#!/bin/bash
ping_1=$(ping -c 1 www.test.com | tail -1| awk '{print $4}' | cut -d '/' -f 2 | sed 's/\.[^.]*$//')
ping_2=$(ping -c 1 www.test1.com | tail -1| awk '{print $4}' | cut -d '/' -f 2 | sed 's/\.[^.]*$//')
ping_3=$(ping -c 1 www.test2.com | tail -1| awk '{print $4}' | cut -d '/' -f 2 | sed 's/\.[^.]*$//')
ping_4=$(ping -c 1 www.test3.com | tail -1| awk '{print $4}' | cut -d '/' -f 2 | sed 's/\.[^.]*$//' )然后,我想在一个变量中处理ping_1-4的输出。就像这样:
#!/bin/bash
if [ "$ping_*" -gt 50 ]; then
echo "One ping is to high"
else
echo "The pings are fine"
fi在bash中是否存在用某种通配符读取这些变量的可能性?
$ping_*没有为我做任何事。
发布于 2016-10-30 16:34:40
我不认为有这样的通配符。但是您可以使用一个循环来迭代值,例如:
exists_too_high() {
for value; do
if [ "$value" -gt 50 ]; then
return 0
fi
done
return 1
}
if exists_too_high "$ping_1" "$ping_2" "$ping_3" "$ping_4"; then
echo "One ping is to high"
else
echo "The pings are fine"
fi发布于 2016-10-30 16:58:27
您所指出的问题的答案是,是的,您可以使用bash (但不是sh)中的参数展开来实现这一点:
#!/bin/bash
ping_1=foo
ping_2=bar
ping_etc=baz
for var in "${!ping_@}"
do
echo "$var is set to ${!var}"
done将打印
ping_1 is set to foo
ping_2 is set to bar
ping_etc is set to baz这是man bash
${!prefix*}
${!prefix@}
Names matching prefix. Expands to the names of variables whose
names begin with prefix, separated by the first character of the
IFS special variable. When @ is used and the expansion appears
within double quotes, each variable name expands to a separate
word.解决实际问题的方法是使用数组。
发布于 2016-10-30 16:41:38
您可以使用"and“(-a) param:
if [ $ping_1 -gt 50 -a \
$ping_2 -gt 50 -a \
$ping_3 -gt 50 -a ]; then
...
...或者,您可以创建一个数组并使用一个循环进行检查,而不是定义许多变量:
pings+=($(ping -c 1 www.test.com | tail -1| awk '{print $4}' | cut -d '/' -f 2 | sed 's/\.[^.]*$//'))
pings+=($(ping -c 1 www.test1.com | tail -1| awk '{print $4}' | cut -d '/' -f 2 | sed 's/\.[^.]*$//'))
pings+=($(ping -c 1 www.test2.com | tail -1| awk '{print $4}' | cut -d '/' -f 2 | sed 's/\.[^.]*$//'))
pings+=($(ping -c 1 www.test3.com | tail -1| awk '{print $4}' | cut -d '/' -f 2 | sed 's/\.[^.]*$//' ))
too_high=0
for ping in ${pings[@]}; do
if [ $ping -gt 50 ]; then
too_high=1
break
fi
done
if [ $too_high -eq 1 ]; then
echo "One ping is to high"
else
echo "The pings are fine"
fihttps://stackoverflow.com/questions/40331108
复制相似问题