小编典典

让bash处理来自管道的stdin的数据

linux

我试图让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"也不起作用。


阅读 536

收藏
2020-06-02

共1个答案

小编典典

采用

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

可以read像这样欺骗从管道中接受:

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

甚至编写这样的函数:

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

但是没有意义-您的变量分配可能不会持续!管道可能会产生一个子外壳,其中环境是通过值而不是通过引用继承的。这就是为什么read不打扰管道输入的原因-
它是未定义的。

仅供参考,http://www.etalabs.net/sh_tricks.html是打击bourne贝壳sh的怪异和不兼容所必需的精巧的草皮收藏。

2020-06-02