[u-u] wow, post-tested loops in sh
Alan J Rosenthal
flaps at 56789.ca
Sun Jul 3 22:12:28 EDT 2016
Greetings,
I think I know sh programming pretty thoroughly, and one of the things I
know is that there is no post-tested loop in sh.
I seem to have been wrong about that. Sort of.
Compare the C program snippets:
while (i < 5) {
printf("%d\n", i);
i = i + 1;
}
and
do {
printf("%d\n", i);
i = i + 1;
} while (i < 5);
They behave the same so long as i<5 initially. However, if it is not
the case that i<5 initially, the second iterates once anyway, whereas
the first doesn't. Of course this normally means we want the first,
but there do exist cases where we want the second.
So, here's the former in sh, adding "i=$1" at the beginning to make it easier
to run this with various values to play with it:
i=$1
while test $i -lt 5
do
echo $i
i=`expr $i + 1`
done
And now, my new learning gives me the following in sh as the post-tested-loop
version (I'm not entirely sure how to indent it though):
i=$1
while
echo $i
i=`expr $i + 1`
test $i -lt 5
do :
done
where ":" is the null statement, and the statement separator after the "do" is
for some reason optional (I did already know that). (In sh, control
constructs have as their body "one or more statements" instead of the more
modern "zero or more statements".)
All this follows from the syntax of the 'while' statement, but still, wow.
I still wouldn't actually use this in code I expected anyone to read, which
means that I wouldn't actually use this.
(A more usual formatting of the above, reflecting that this really is
technically a pre-tested loop, would be:
i=$1
while echo $i; i=`expr $i + 1`; test $i -lt 5
do
:
done
)
regards,
ajr
More information about the u-u
mailing list