BashScripts.org
http://bashscripts.org/forum/

difference between bash and other shells with "while"
http://bashscripts.org/forum/viewtopic.php?f=16&t=1003
Page 1 of 1

Author:  allegre [ Wed Feb 24, 2010 1:15 pm ]
Post subject:  difference between bash and other shells with "while"

Hello, a strange behaviour of while with bash 4.0.28 :

Code:
$ A=1 ; while [ $A -lt 4 ] ; do A=$((A+1)); echo $A ; done ; echo $A
2
3
4
4


Code:
$ A=1 ; cat foobar |while [ $A -lt 4 ] ; do A=$((A+1)); echo $A ; done ; echo $A
2
3
4
1


My first question : after a pipe, while does'nt keep the value for variable $A. Why ?

My second question : dash behaves like bash, but zsh and ksh have a more "normal" behaviour : the 2 variants end with $A=4.
Is there a good reason ? Posix compatibility or somewhat ?

(foobar is a real file, but it's the same if it doesn't exist)

Author:  DarthWavy [ Thu Feb 25, 2010 4:13 am ]
Post subject:  Re: difference between bash and other shells with "while"

I can't explain exactly why but when one uses a pipe into a loop in bash it creates a subshell for the loop, which creates the weirdness with the scope of variables.
For this specific instance you can replace your useless use of cat with a fix;

Code:
#] A=1 ; while [ $A -lt 4 ] ; do A=$((A+1)); echo $A ; done < foobar ; echo $A
2
3
4
4


Of course for this one the file must exist.
This is an example of why I don't use bash for larger or more complex tasks, preferring perl instead.

Page 1 of 1 All times are UTC - 6 hours
© 2000, 2002, 2005, 2007 phpBB Group • http://www.phpbb.com