Unexpected / Inconsistent shell behaviour
A while ago I was working with a system shell script and encountered a really unexpected result when I tried to do something a certain way. Below I've distilled it into a simple example. Odd shell behaviour of some sort has been discussed on this forum before, but I couldn't find it, so I hope this isn't a duplicate discussion.
Consider the following example script for a Bourne-like shell:
#!/path/to/shell VAR=Old echo A | while read REPLY; do echo Here VAR=New done echo VAR = $VAR
At this point, to get the most out of this, you shouldn't read past the end of this paragraph. Just study the script above and decide what you think the output should be. Then come back and read the rest of the post. No cheating now, look at the script first.
When I ran the script on "most" shells, the output was totally unexpected. It gave this:
Note that since it prints "Here", the script does go into the do loop where VAR gets set to New. Yet upon exiting the loop, VAR is back to the "Old" value! It's as if what happens in the loop is somehow quite local, and is lost after leaving the loop. I got this weird behaviour with the following shells:
The output I'd expected was this:
After checking more shells, this output was produced by:
One conclusion is that Bourne-like shells are not consistent about this.
Question: Is the "locality" of the unexpected output intended and is it documented somewhere? I looked at some man pages a bit and didn't find anything, but maybe it's subtle or I plain missed it.
Thanks for reading, and for any comments.
|Thread||Thread Starter||Forum||Replies||Last Post|
|Identify rules to behaviour||Droid||OpenBSD Security||5||25th March 2012 06:58 PM|
|DragonflyBSD: unexpected pkg_admin running.||colonelmooch||Other BSD and UNIX/UNIX-like||0||4th August 2011 05:26 PM|
|Am I blind? syntax error: `(' unexpected||guitarscn||Programming||1||10th November 2010 08:53 PM|
|strange behaviour after improper shutdown||karri||FreeBSD General||1||15th October 2008 04:08 PM|
|Funny network behaviour :)||PatrickBaer||General software and network||5||9th October 2008 10:47 AM|