|
|
|
|
|||||||||||||||||||||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
wierd while loop result
Hi, Friends,
In the following simple code, the WHILE LP doesn't give the result I expected. Did I do it wrong? You can create a config.txt with 3 lines (can be anything) in it. and then run mytest.sh The final a is 0, instead of 3. not sure why. Is the a in the while loop a local variable which in only available inside the loop, not outside the loop? Thanks. script mytest.sh #!/bin/sh a=0 b=0 while read line do a=`expr $a + 1` echo now a is $a done < config.txt echo "finally a is $a" for i in x y z do b=`expr $b + 1` echo now b is $b done echo finally b is $b |
|
#2
|
|||
|
|||
|
wierd while loop result
BILL wrote:
Hi, Friends, > In the following simple code, the WHILE LP doesn't give the result I expected. Did I do it wrong? > You can create a config.txt with 3 lines (can be anything) in it. and then run mytest.sh > The final a is 0, instead of 3. not sure why. Is the a in the while loop a local variable which in only available inside the loop, not outside the loop? Thanks. > script mytest.sh #!/bin/sh a=0 b=0 while read line do a=`expr $a + 1` echo now a is $a done < config.txt echo "finally a is $a" for i in x y z do b=`expr $b + 1` echo now b is $b done echo finally b is $b The while loop is a block. The traditional Unix sh runs this in a sub-shell. According to the Unix principal a child process inherits all settings and cannot give anything back but the exit code. My observation is that Posix shells don't do this, unless forced by a pipe. Unlike the while loop, the for loop is never treated as a block. -- echo imhcea\.lophc.tcs.hmo | sed 's2\(\)\(.\{5\}\)2\2\122;s1\(.\)\(.\)1\2\11g;1s;\. ;::;2' |
|
#3
|
|||
|
|||
|
wierd while loop result
Michael Tosch wrote:
The while loop is a block. That's not the relevant point. It's about the redirection: Redirection of a command (other than a simple-command) causes a sub-shell to be created. Such non-simple commands are control structures like "while", "for" and "if", but also "{ list;}", My observation is that Posix shells don't do this, unless forced by a pipe. You can even narrow it down to traditional Bourne shells. BTW: Using a pipeline is a different issue, though. And the usage of "forced" here is misleading: PSIX doesn't determine whether (the last element of) a pipeline is a separate environment or not. And among the implementations you will find both ways. Unlike the while loop, the for loop is never treated as a block. Well, you should try it :) |
![]() |
| Viewing: Web Development Archives > FAQs > Unix/Linux > wierd while loop result |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|