linux - 从管道将值读入 shell 变量

我试图让 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/

相关文章:

linux - 对标准输入、标准输出和标准错误感到困惑?

python - 如何在 Python 列表中切换两个项目的位置?

Android Debug Bridge (adb) 设备 - 无权限

python - 将 numpy dtypes 转换为原生 python 类型

linux - 如何在 Minikube 中使用本地 docker 镜像?

python - 错误 : command 'gcc' failed with exit statu

python - 如何避免 "RuntimeError: dictionary changed si

linux - fork()、vfork()、exec()和clone()的区别

python - 如何比较 Python 中的版本号?

python - python - 如何按两列或多列对python pandas中的dataFram