我试图让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"; };

输出为:

test = hello world

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

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

其他回答

Use

IFS= read var << EOF
$(foo)
EOF

你可以像这样诱使read从管道中接受:

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

或者写一个这样的函数:

read_from_pipe() { read "$@" <&0; }

但这没有意义——你的可变任务可能不会持久!管道可以生成子shell,其中环境是按值继承的,而不是按引用继承的。这就是为什么read不打扰管道的输入——它是未定义的。

仅供参考,http://www.etalabs.net/sh_tricks.html是一个漂亮的cruft收集必要的战斗奇怪和不兼容的伯恩炮弹,sh。

这是另一种选择

$ read test < <(echo hello world)

$ echo $test
hello world

Read不会从管道中读取(或者可能因为管道创建了子shell而导致结果丢失)。然而,你可以在Bash中使用here字符串:

$ read a b c <<< $(echo 1 2 3)
$ echo $a $b $c
1 2 3

但是关于lastpipe的信息,请参阅@chepner的回答。

因为我上当了,我想留个便条。 我发现了这个线程,因为我必须重写一个旧的sh脚本 POSIX兼容。 这基本上意味着绕过POSIX引入的管道/子shell问题,重写如下代码:

some_command | read a b c

成:

read a b c << EOF
$(some_command)
EOF

代码是这样的:

some_command |
while read a b c; do
    # something
done

成:

while read a b c; do
    # something
done << EOF
$(some_command)
EOF

但后者在空输入时表现不一样。 使用旧的符号,while循环不会在空输入时输入, 但在POSIX符号中它是! 我认为这是由于EOF之前的换行, 这一点不容忽视。 POSIX代码的行为更像旧的符号 看起来是这样的:

while read a b c; do
    case $a in ("") break; esac
    # something
done << EOF
$(some_command)
EOF

在大多数情况下,这就足够了。 但不幸的是,这仍然不完全像以前的符号 如果some_command打印空行。 在旧的表示法中,执行while主体 在POSIX符号中,我们在主体前面中断。

解决这个问题的方法是这样的:

while read a b c; do
    case $a in ("something_guaranteed_not_to_be_printed_by_some_command") break; esac
    # something
done << EOF
$(some_command)
echo "something_guaranteed_not_to_be_printed_by_some_command"
EOF

以下代码:

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。