How to use the read command in Bash?

前端 未结 8 1761
执念已碎
执念已碎 2020-12-07 23:54

When I try to use the read command in Bash like this:

echo hello | read str
echo $str

Nothing echoed, while I think str<

相关标签:
8条回答
  • 2020-12-08 00:36

    I really only use read with "while" and a do loop:

    echo "This is NOT a test." | while read -r a b c theRest; do  
    echo "$a" "$b" "$theRest"; done  
    

    This is a test.
    For what it's worth, I have seen the recommendation to always use -r with the read command in bash.

    0 讨论(0)
  • 2020-12-08 00:41

    Another alternative altogether is to use the printf function.

    printf -v str 'hello'
    

    Moreover, this construct, combined with the use of single quotes where appropriate, helps to avoid the multi-escape problems of subshells and other forms of interpolative quoting.

    0 讨论(0)
  • 2020-12-08 00:47

    To put my two cents here: on KSH, reading as is to a variable will work, because according to the IBM AIX documentation, KSH's read does affects the current shell environment:

    The setting of shell variables by the read command affects the current shell execution environment.

    This just resulted in me spending a good few minutes figuring out why a one-liner ending with read that I've used a zillion times before on AIX didn't work on Linux... it's because KSH does saves to the current environment and BASH doesn't!

    0 讨论(0)
  • 2020-12-08 00:48

    The read in your script command is fine. However, you execute it in the pipeline, which means it is in a subshell, therefore, the variables it reads to are not visible in the parent shell. You can either

    • move the rest of the script in the subshell, too:

      echo hello | { read str
        echo $str
      }
      
    • or use command substitution to get the value of the variable out of the subshell

      str=$(echo hello)
      echo $str
      

      or a slightly more complicated example (Grabbing the 2nd element of ls)

      str=$(ls | { read a; read a; echo $a; })
      echo $str
      
    0 讨论(0)
  • 2020-12-08 00:49

    Do you need the pipe?

    echo -ne "$MENU"
    read NUMBER
    
    0 讨论(0)
  • 2020-12-08 00:50

    The value disappears since the read command is run in a separate subshell: Bash FAQ 24

    0 讨论(0)
提交回复
热议问题