There is the well known while condition; do ...; done
loop, but is there a do... while
style loop that guarantees at least one execution of the block?
Shell – do…while or do…until in POSIX shell script
control flowshell
control flowshell
There is the well known while condition; do ...; done
loop, but is there a do... while
style loop that guarantees at least one execution of the block?
Best Answer
A very versatile version of a
do ... while
has this structure:An example is:
As it is (no value set for
i
) the loop executes 20 times.UN-Commenting the line that sets
i
to 16i=16
, the loop is executed 4 times.For
i=16
,i=17
,i=18
andi=19
.If i is set to (let's say 26) at the same point (the start), the commands still get executed the first time (until the loop break command is tested).
The test for a while should be truthy (exit status of 0).
The test should be reversed for an until loop, i.e.: be falsy (exit status not 0).
A POSIX version needs several elements changed to work: