Answers:
一个非常通用的版本do ... while
具有以下结构:
while
Commands ...
do :; done
一个例子是:
#i=16
while
echo "this command is executed at least once $i"
: ${start=$i} # capture the starting value of i
# some other commands # needed for the loop
(( ++i < 20 )) # Place the loop ending test here.
do :; done
echo "Final value of $i///$start"
echo "The loop was executed $(( i - start )) times "
照原样(未设置的值i
),循环执行20次。
取消注释设置i
为16 的行,i=16
循环将执行4次。
对于i=16
,i=17
,i=18
和i=19
。
如果在同一点(开始)将i设置为(假设为26),则命令仍将在第一次执行(直到测试loop break命令)。
一段时间的测试应该是真实的(退出状态为0)。
测试应反向进行直至循环,即:虚假(退出状态不为0)。
POSIX版本需要更改几个元素才能起作用:
i=16
while
echo "this command is executed at least once $i"
: ${start=$i} # capture the starting value of i
# some other commands # needed for the loop
i="$((i+1))" # increment the variable of the loop.
[ "$i" -lt 20 ] # test the limit of the loop.
do :; done
echo "Final value of $i///$start"
echo "The loop was executed $(( i - start )) times "
./script.sh
this command is executed at least once 16
this command is executed at least once 17
this command is executed at least once 18
this command is executed at least once 19
Final value of 20///16
The loop was executed 4 times
set -e
在while条件块内使用任何失败的方法都不会停止执行:例如set -e; while nonexistentcmd; true; do echo "SHiiiiit"; exit 3; done
->发生狗屎。因此,如果您使用此命令,则必须非常小心错误处理,即用&&
!链接所有命令。
没有do ... while或do ... until循环,但是可以像这样完成同一件事:
while true; do
...
condition || break
done
直到:
until false; do
...
condition && break
done