我试图让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”周围加上“”引号,但也不起作用。


当前回答

以下代码:

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

将工作太,但它将打开另一个新的子壳后管道,在哪里

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

不会的。


我必须禁用作业控制来使用chepnars的方法(我从终端运行这个命令):

set +m;shopt -s lastpipe
echo "hello world" | read test; echo test=$test
echo "hello world" | test="$(</dev/stdin)"; echo test=$test

Bash手册说:

lastpipe 如果设置了,并且作业控制不处于活动状态,shell将运行最后一条命令 没有在当前shell的后台执行的管道 环境。

注意:在非交互式shell中,作业控制默认是关闭的,因此在脚本中不需要set +m。

其他回答

第一次尝试非常接近。这种变化应该是有效的:

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

输出为:

test = hello world

在管道后面需要用大括号括起要测试的赋值和回显。

如果没有大括号,test的赋值(在管道之后)在一个shell中,而echo "test=$test"在一个单独的shell中,该shell不知道该赋值。这就是为什么在输出中得到"test="而不是"test=hello world"。

这是另一种选择

$ read test < <(echo hello world)

$ echo $test
hello world

将一些内容输出到包含赋值的表达式中就不是这样了。

相反,尝试:

test=$(echo "hello world"); echo test=$test

这个怎么样:

echo "hello world" | echo test=$(cat)

从shell命令到bash变量的隐式管道的语法为

var=$(command)

or

var=`command`

在示例中,将数据输送到赋值语句,该语句不需要任何输入。