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

Sha*_*off 22 shell control-flow

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

小智 24

一个非常通用的 a 版本do ... while具有以下结构:

while 
      Commands ...
do :; done
Run Code Online (Sandbox Code Playgroud)

一个例子是:

#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 "
Run Code Online (Sandbox Code Playgroud)

照原样(没有为 设置值i)循环执行 20 次。
取消注释设置i为 16的行,i=16循环执行 4 次。
对于i=16i=17i=18i=19

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

一段时间的测试应该是真的(退出状态为 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 "
Run Code Online (Sandbox Code Playgroud)
./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 
Run Code Online (Sandbox Code Playgroud)

  • 请记住,如果您使用“set -e”,则 while 条件块内的任何失败都不会停止执行:例如“set -e;” 而不存在cmd;真的; 回显“SHiiiit”;3号出口;完成`-&gt; 糟糕的事情发生了。所以,如果你使用这个,你必须非常小心错误处理,即用“&amp;&amp;”链接所有命令! (2认同)

Sha*_*off 21

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

while true; do
  ...
  condition || break
done
Run Code Online (Sandbox Code Playgroud)

直到:

until false; do
  ...
  condition && break
done
Run Code Online (Sandbox Code Playgroud)