从管道中读取数值到一个shell变量

我试图让bash处理来自stdin的数据,这些数据被管道输入,但没有成功。我的意思是,下面这些方法都不能工作。

echo "hello world" | test=($(< /dev/stdin)); echo test=$test
test=

echo "hello world" | read test; echo test=$test
test=

echo "hello world" | test=`cat`; echo test=$test
test=

我希望输出为 "test=hello world"。我试着在""周围加上引号"$test"`,这也不起作用。

read不会从管道中读取(也可能因为管道创建了一个子壳,所以结果会丢失)。然而,你可以在Bash中使用这里的字符串。


$ read a b c 
评论(1)

从一个shell命令到一个bash变量的隐含管道的语法是

var=$(command)

var=`command`

在你的例子中,你把数据输送到一个不需要任何输入的赋值语句。

评论(4)

在涉及到赋值的表达式中加入一些东西并不会有这样的表现。

相反,请尝试。

test=$(echo "hello world"); echo test=$test
评论(0)