我试图让 bash 处理来自标准输入的数据,这些数据通过管道输入,但没有运气。我的意思是没有以下工作:
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"
周围加上 ""引号,但这也不起作用。
最佳答案
使用
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是对抗 bourne shell 的怪异和不兼容所必需的精美集合,sh。
https://stackoverflow.com/questions/2746553/