如何在bash使用读命令? [英] how to use read command in bash?
本文介绍了如何在bash使用读命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试在bash使用读命令:
when I try to use 'read' command in bash:
echo hello | read str
echo $str
没有回应,而我觉得STR应该包含'你好'。
任何人可以帮助我吗?
Nothing echoed, while I think str should contain 'hello'. Can anybody help me?
推荐答案
的读
在你的脚本的命令是好的。但是,在管道,这意味着它是在一个子shell执行它,因此,它会读取到变量不在父shell可见。您可以
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
-
移动脚本的其余部分中的子shell,太:
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
或稍微复杂的例子。
str=$(ls | { read a; read a; echo $a; })
echo $str
这篇关于如何在bash使用读命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文