Hacker News new | past | comments | ask | show | jobs | submit login

> 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



Ah, 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.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: