从管道将值读入 shell 变量 [英] Read values into a shell variable from a pipe
问题描述
我试图让 bash 处理来自 stdin 的数据,这些数据通过管道输入,但没有运气.我的意思不是以下工作:
I am trying to get bash to process data from stdin that gets piped into, but no luck. What I mean is none of the following work:
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"
周围加上 "" 引号也不起作用.
where I want the output to be test=hello world
. I've tried putting "" quotes around "$test"
that doesn't work either.
推荐答案
使用
IFS= read var << EOF
$(foo)
EOF
你可以欺骗read
从管道接受这样的:
You can trick read
into accepting from a pipe like this:
echo "hello world" | { read test; echo test=$test; }
甚至写一个这样的函数:
or even write a function like this:
read_from_pipe() { read "$@" <&0; }
但是没有意义——你的变量赋值可能不会持续!管道可能会产生一个子外壳,其中的环境是通过值继承的,而不是通过引用继承的.这就是为什么 read
不关心来自管道的输入 - 它是未定义的.
But there's no point - your variable assignments may not last! A pipeline may spawn a subshell, where the environment is inherited by value, not by reference. This is why read
doesn't bother with input from a pipe - it's undefined.
仅供参考,http://www.etalabs.net/sh_tricks.html 很不错收集必要的 cruft 以对抗 bourne shell 的奇怪和不兼容,sh.
FYI, http://www.etalabs.net/sh_tricks.html is a nifty collection of the cruft necessary to fight the oddities and incompatibilities of bourne shells, sh.
这篇关于从管道将值读入 shell 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!