在POSIX shell脚本中执行…while或do…until


16

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


非常感谢Shawn,我没想到答案会这么快成为所选答案。所以:感谢您的选择。

Answers:


15

一个非常通用的版本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),则命令仍将在第一次执行(直到测试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->发生狗屎。因此,如果您使用此命令,则必须非常小心错误处理,即用&&!链接所有命令。
蒂莫

17

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

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

直到:

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

您可以在任一循环中使用任意一条折线-当为true或直到false时,表示“永远”。我了解这有点保留了“高兴退出”或“悲伤退出”的条件。
android.weasel 2015年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.