For循环没有以bash给出预期的输出

时间:2018-08-29 13:08:58

标签: bash shell grep

我创建了一个脚本来从文件中查找多个字符串。但是不需要长输出。 并希望获得以下输出。 例如:如果所有字符串都匹配,则回显All nodes are UP否则返回WEB1 WEB2 down 如果在该文件中找不到WEB1和WEB2。

下面是我的脚本以及输出:

arr=("WEB1" "WEB2" "WEB3" "WEB4" "WEB5" "WEB6" "WEB7" "WEB8" "WEB9" "WEB10" "pro-webs3")

for i in ${arr[@]}
do
  if grep -w "$i" Filename >> /dev/null
then
echo $i >> /dev/null
echo "node are up"
else
echo "$i Node is down"
fi
done

输出:

WEB1 Node is down
All nodes are up
All nodes are up
All nodes are up
All nodes are up
All nodes are up
All nodes are up
All nodes are up
All nodes are up
All nodes are up
pro-webs3 Node is down

1 个答案:

答案 0 :(得分:2)

创建故障节点数组并采取相应的措施:列出不为空的节点。

arr=("WEB1" "WEB2" "WEB3" "WEB4" "WEB5" "WEB6" "WEB7" "WEB8" "WEB9" "WEB10" "pro-webs3")
failed=()

for i in "${arr[@]}"
do
  if ! grep -q -w "$i" Filename
  then
    failed+=("$i")
  fi
done

if [ "${#failed[@]}" -eq 0 ]
then
    echo "All nodes are UP"
else
    echo "${failed[@]} DOWN"
fi