Search code examples
bashbuilt-in

How to use the read command in Bash?


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

echo hello | read str
echo $str

Nothing echoed, while I think str should contain the string hello. Can anybody please help me understand this behavior?


Solution

  • 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