View Single Post
  #1   (View Single Post)  
Old 20th May 2013
IdOp's Avatar
IdOp IdOp is offline
Too dumb for a smartphone
Join Date: May 2008
Location: twisting on the daemon's fork(2)
Posts: 833
Default 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:



echo A | while read REPLY; do

    echo Here



echo VAR = $VAR
Note that the first line of the script (in red) shouldn't be used literally. Replace it with paths to various Bourne-like shells to be tested.

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.

Unexpected Behaviour

When I ran the script on "most" shells, the output was totally unexpected. It gave this:

VAR = Old

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:

sh NetBSD
ksh NetBSD
ksh OpenBSD
sh SunOS

Expected Behaviour

The output I'd expected was this:

VAR = New

After checking more shells, this output was produced by:

ksh93 CentOS
ksh SunOS

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.
Reply With Quote