DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   Shell Scripting (http://www.daniweb.com/forums/forum113.html)
-   -   Arithmetic Evaluation and Pipes in BASH (http://www.daniweb.com/forums/thread20134.html)

chrissi Mar 13th, 2005 6:49 pm
Arithmetic Evaluation and Pipes in BASH
 
Hi,

I had some irritation with a "while"- loop, which turned out to be endless.
Anyway, i was able to find the problem and reduce it to be shown on the commandline:

I "typeset" (and initialize) an array and an integer variable:
$ typeset -a arr; arr=(bourne again shell)
$ typeset -i ind=0

Everything works as expected when doing:
$ echo ${arr[((ind++))]}
bourne
$ echo ${arr[((ind++))]}
again
$ echo ${arr[((ind++))]}
shell

But when i use the "echo" command in a pipe, (like:)
$ typeset -i ind=0
$ echo ${arr[((ind++))]} | grep e
bourne

the postincrement of "ind" is not evaluated, so the next time i also get:
$ echo ${arr[((ind++))]} | grep e
bourne
$ echo ${arr[((ind++))]} | grep e
bourne

Well, this is not really a problem for i can do it in two lines, but i wonder, if it's possible to make it work in one line.

Anywone who can give a comment?

Thanks for reading and trying to help!
Bye,
Christoph

atucsprof Jun 26th, 2009 12:28 pm
Re: Arithmetic Evaluation and Pipes in BASH
 
Christoph,

The answer is that every member of a pipeline is turned into a separate process with its own environment. So changing the variable in a pipeline changes it in a subshell and not the current shell.

You'll have to change the value of the variable after invoking the pipe.


Quote:

Originally Posted by chrissi (Post 101450)
Hi,

I had some irritation with a "while"- loop, which turned out to be endless.
Anyway, i was able to find the problem and reduce it to be shown on the commandline:

I "typeset" (and initialize) an array and an integer variable:
$ typeset -a arr; arr=(bourne again shell)
$ typeset -i ind=0

Everything works as expected when doing:
$ echo ${arr[((ind++))]}
bourne
$ echo ${arr[((ind++))]}
again
$ echo ${arr[((ind++))]}
shell

But when i use the "echo" command in a pipe, (like:)
$ typeset -i ind=0
$ echo ${arr[((ind++))]} | grep e
bourne

the postincrement of "ind" is not evaluated, so the next time i also get:
$ echo ${arr[((ind++))]} | grep e
bourne
$ echo ${arr[((ind++))]} | grep e
bourne

Well, this is not really a problem for i can do it in two lines, but i wonder, if it's possible to make it work in one line.

Anywone who can give a comment?

Thanks for reading and trying to help!
Bye,
Christoph



All times are GMT -4. The time now is 3:52 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC