Read values into a shell variable from a pipe

2019-01-03 04:11发布

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=

where I want the output to be test=hello world. I've tried putting "" quotes around "$test" that doesn't work either.

标签: linux bash pipe
14条回答
Emotional °昔
2楼-- · 2019-01-03 04:44

The syntax for an implicit pipe from a shell command into a bash variable is

var=$(command)

or

var=`command`

In your examples, you are piping data to an assignment statement, which does not expect any input.

查看更多
forever°为你锁心
3楼-- · 2019-01-03 04:44

Piping something into an expression involving an assignment doesn't behave like that.

Instead, try:

test=$(echo "hello world"); echo test=$test
查看更多
登录 后发表回答