4 ms·
One thing to be careful of when doing "while read..." is that a new shell is started on each iteration, so you cannot for example set a variable within the loop
by joseph 13y ago
One thing to be careful of when doing "while read..." is that a new shell is started on each iteration, so you cannot for example set a variable within the loop that you can use later in the script, as its value will be lost when the shell process exits.
- sigil 13y ago> a new shell is started on each iteration This is not actually true. printf "\n\n\n" | while read i; do a="x$a"; echo "$a"; done x xx xxx The accumulator value even carries over after the while loop: printf "\n\n\n" | ( while read i; do a="x$a"; echo "$a"; done ; echo "$a" ) x xx xxx xxx (Technically, whether or not the loop body is executed in a subshell may be implementation dependent. Haven't looked at the POSIX shell spec in a while, but I seem to remember an old ksh that actually used subshells. At any rate, none of the modern sh's and bash force a subshell.) What is true, however, is that a pipeline will execute in a subshell. Maybe that's what you're getting at here, and it is an important caveat. a=y; printf "\n\n\n" | while read i; do a="x$a"; echo "$a"; done; echo "$a" xy xxy xxxy y
- joseph 13y agoAh, ok. True, when I have had this issue it was after doing something like 'grep "pattern" file | while read ...'. I did not realize it was the pipe that caused this.