POSIX シェルスクリプトで do...while または do...until

POSIX シェルスクリプトで 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回実行されます。 16に設定された行の
コメントを解除し、4回繰り返します。 、および。ii=16
i=16i=17i=18i=19

iが同じポイント(開始)で(26と仮定)設定されると、コマンドは最初に実行されます(テストループがコマンドを中断するまで)。

テストはしばらく真でなければなりません(終了ステータスは0です)。
Untilループの場合、テストは反対でなければなりません。つまり、false(終了状態がゼロではない)でなければなりません。

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 

おすすめ記事