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

前端 未结 8 1747
慢半拍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:31

    alternative:

    echo foo | (read a ; echo $a)
    

    Edit:

    If you need $a outside the subshell, you have to reverse the commands:

    read a < <(echo foo); echo $a
    

    this way the read is executed in the current process

    0 讨论(0)
  • 2021-02-04 16:31

    I came up with a solution that doesn't hide the variable values in a subshell, and that can also work with multiple values.

    set `echo foo bar`
    A=$1
    B=$2
    
    0 讨论(0)
提交回复
热议问题