Scrutinizer and i had a discussion about loops in shell scripts and you might be interested in joining in and share your experiences:
i wrote an example script which basically employed the following logic:
cat /some/file | while read var ; do
echo var = $var # just do something with $var
done
Scrutinizer said, this is a UUOC. Well, in principle, he is of course right. We could write the same this way:
while read var ; do
echo var = $var # just do something with $var
done < /some/file
But still, i beg to differ. This is not a useless but a very sensible use of cat! Suppose the loop would not be as short as the example here, but several screenpages long. To understand what goes into "$var" one would have to scroll down to its end, then, to find out what is done with "$var", scroll back up again.
Is it only me that i hate to have to scroll up and down repeatedly? I find it a lot easier to read if i "steer my loops from the top" instead of from the (maybe far-away) bottom.
Of course, there is this alluring GNU shellnik startup called bash. In bash pipelines have some really weird side effects, like variables being local to them. The following works in both shells:
cat /some/list | while read entry ; do
line="$line $entry"
done
echo $line # what is in there?
But while in ksh "$line" would hold all the list entries after the loop in bash the variable would be empty! Is it only me or do you think this is counter-intuitive too?
So probably in bash one has to resort to this ugly style of meticulously telling the shell the recipe in length while being totally silent about the ingredients you want to use - until the very end. Could you imagine cook books to be written that way? It would look like:
But the question stays: do you think this - in strictest terms - UUOC should be avoided even if it has no negatie side effects or do you think the gain in clarity outweighs this?
Discuss!
bakunin