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이라고 가정) 설정되면 명령은 처음 실행됩니다(테스트 루프가 명령을 중단할 때까지).

테스트는 잠시 동안 true여야 합니다(종료 상태는 0입니다).
Until 루프의 경우 테스트는 반대여야 합니다. 즉, false(종료 상태가 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

관련 정보