I wasn’t sure where I can put it, but I am confused why I am getting different results trying to do (seemingly) same thing in bash and zsh shell. Here are a lot of experienced users and maybe somebody can clarify it a bit or give a helpful hint of what’s wrong. Basically if I run something of the sort in bash and zsh shells:
x=0 && echo -e "First\nSecond\nThird" | while read line; do echo $line && ((++x)); done; echo $x
In bash the output is always the original value of the variable x (0 in this case). While in zsh it seems to be incremented correctly and I am getting 3 (like I’d expect).
It would seem as if (in bash) the variable x was shadowed by another copy inside the while
block which was destroyed at the end of the block, so the value of the original outer variable was read. But checking with something like:
x=1; while [ $x -lt 3 ]; do ((++x)); done; echo $x
I see that it’s not the case, as I am getting the correct output (3) in both shells.
So, the case must be in the read utility then? I guess bash respects the read’s POSIX compliant definition and basically it does what the manpages say and zsh uses some builtin version of read? Or I am totally overthinking it and it’s something dead simple (I am new to shells and using zsh pretty much exclusively).
Other shells
ksh’s output is identical to that of zsh, while sh’s is equal to bash’s. Couldn’t get it working in fish, because fish is weird