How to use the read command in Bash?

前端 未结 8 1774
执念已碎
执念已碎 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: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
      

提交回复
热议问题