我一直在写一个脚本,将运行在while循环无限次
如果满足所有条件,则只有脚本会中断并执行另一个命令
My code:
while true
do
# Note : below field will execute some command and generate value
field1=`some command which gives status`
field2=`some command which gives status`
field3=`some command which gives status`
field4=`some command which gives status`
if [ "$field1" == "A" ] && [ "$field2" == "A" ] && [ "$field3" == "A" ] && [ "$field4" == "A" ]
then
break
else
echo "Conditions are not met !!!"
fi
done
echo "Another command execution started ... "
这里的问题是字段的数量可能会变化
需要使我的脚本通用,如果我有10个字段,它也应该框架一个
if
条件,并开始执行,直到所有字段都等于A,并中断执行另一个命令
假设一切"成功";返回状态为A
,为单个字符长度。
可以将所有返回的状态码聚合成一个长字符串。然后尝试搜索非A
值。
local ret_val=""
while true; do
# Note : below field will execute some command and generate value
ret_val="${ret_val}$(some command1 which gives status)"
ret_val="${ret_val}$(some command2 which gives status)"
ret_val="${ret_val}$(some command3 which gives status)"
ret_val="${ret_val}$(some command4 which gives status)"
if [[ ${ret_val} =~ "[^A]*" ]]; then
echo "Conditions are not met !!!"
else
break
fi
done
echo "Another command execution started ... "
如果一切都"成功";返回状态是一个多位数。
您可以将数字返回状态转换为单个字符,参见此回答。
像这样?但这只适用于单行结果
A="A"
output="something to start"
until [ -z "$(echo $output | grep -v $A)" ]
do
output=$(cat <<EOF
`cat A` # First command
`cat B` # Second command
EOF
)
echo "Waiting for condition"
sleep 1
done
你可以试着
echo "A" > A
echo "B" > B
停止条件
echo "A" > B
为您的字段使用数组可以让您对它们进行循环,并将其放在函数中可以让您使用return
来结束执行,即使在多个嵌套循环中:
poll() {
while true; do
declare -a fields=( )
# Note : below field will execute some command and generate value
fields[1]=`some command which gives status`
fields[2]=`some command which gives status`
fields[3]=`some command which gives status`
fields[4]=`some command which gives status`
any_bad=0
for field_idx in "${!fields[@]}"; do
field_val=${fields[$field_idx]}
if [[ $field_val != "A" ]]; then
echo "Conditions not met (field $field_idx is not $field_val, not A)" >&2
any_bad=1
break
fi
done
(( any_bad == 0 )) && return
done
}
poll
所以只要检查A
以外的任何行。
res=$(
some command which gives status
some command which gives status
some command which gives status
some command which gives status
)
if <<<"$res" grep -xFqv A; then
echo "Conditions is not met !!!"
fi