Why is “echo foo | read a ; echo $a” not working as expected?

前端 未结 8 1748
慢半拍i
慢半拍i 2021-02-04 15:37

I could replicate the problem with various shells under FreeBSD, GNU/Linux, and Solaris. It had me head-scratching for more than an hour, so I decided to post the question here

8条回答
  •  臣服心动
    2021-02-04 16:20

    Due to the piping the read is executed in its own subshell.

    echo foo | while read a; do echo $a; done
    

    will do what you expect it to.

提交回复
热议问题