如何在Bash中使用read命令? [英] How to use the read command in Bash?
问题描述
当我尝试像这样在Bash中使用read
命令时:
When I try to use the read
command in Bash like this:
echo hello | read str
echo $str
没有回声,而我认为str
应该包含字符串hello
.有人可以帮我了解这种行为吗?
Nothing echoed, while I think str
should contain the string hello
. Can anybody please help me understand this behavior?
推荐答案
您的脚本命令中的read
很好.但是,您在管道中执行它,这意味着它在子外壳中,因此,它读取的变量在父外壳中不可见.您可以
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
}
或使用命令替换从子shell中获取变量的值
or use command substitution to get the value of the variable out of the subshell
str=$(echo hello)
echo $str
或更复杂的示例(抓取ls的第二个元素)
or a slightly more complicated example (Grabbing the 2nd element of ls)
str=$(ls | { read a; read a; echo $a; })
echo $str
这篇关于如何在Bash中使用read命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!