Register
It is currently Fri Nov 21, 2014 8:57 pm

difference between bash and other shells with "while"


All times are UTC - 6 hours


Post new topic Reply to topic  [ 2 posts ] 
Author Message
 PostPosted: Wed Feb 24, 2010 1:15 pm   

Joined: Wed Feb 24, 2010 1:02 pm
Posts: 1
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)


Top
 Profile  
 PostPosted: Thu Feb 25, 2010 4:13 am   
Moderator
User avatar

Joined: Thu Oct 11, 2007 7:12 am
Posts: 229
Location: London - UK
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.


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 7 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP