在 POSIX shell 脚本中 do...while 或 do...until

在 POSIX shell 脚本中 do...while 或 do...until

有一种众所周知的while condition; do ...; done循环,但是是否有一种do... while样式循环可以保证至少执行一次该块?

答案1

a 的一个非常通用的版本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=16i=17i=18i=19

如果 i 在同一点(开始)设置为(假设为 26),则命令仍然会第一次执行(直到测试循环中断命令)。

测试一段时间应该是 true(退出状态为 0)。
对于until 循环,测试应该相反,即:为假(退出状态不为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 

答案2

没有 do...while 或 do...until 循环,但可以像这样完成同样的事情:

while true; do
  ...
  condition || break
done

直到:

until false; do
  ...
  condition && break
done

相关内容