[英]In bash script, how to use function exit status in while loop condition
下面是我的shell脚本。 如何比较while循环条件块中函数的退出状态? 无论我从check1
函数返回什么,我的代码都会进入 while 循环
#!/bin/sh
check1()
{
return 1
}
while [ check1 ]
do
echo $?
check1
if [ $? -eq 0 ]; then
echo "Called"
else
echo "DD"
fi
sleep 5
done
删除test
命令 - 也称为[
。 所以:
while check1
do
# Loop while check1 is successful (returns 0)
if check1
then
echo 'check1 was successful'
fi
done
从 Bourne 和 POSIX shell 派生的 shell 在条件语句之后执行命令。 一种看待它的方法是while
和if
测试成功或失败,而不是 true 或 false(尽管true
被认为是成功的)。
顺便说一句,如果你必须测试$?
显式(通常不需要)然后(在 Bash 中) (( ))
构造通常更易于阅读,如下所示:
if (( $? == 0 ))
then
echo 'worked'
fi
函数(或命令)执行返回的值存储在 $? 中,一种解决方案是:
check1
while [ $? -eq 1 ]
do
# ...
check1
done
一个更好更简单的解决方案可能是:
while ! check1
do
# ...
done
在这种形式中,零为真,非零为假,例如:
# the command true always exits with value 0
# the next loop is infinite
while true
do
# ...
你可以用!
否定该值:
# the body of the next if is never executed
if ! true
then
# ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.