Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't read fill variables when used at the end of a pipe?

Tags:

linux

bash

Why is the output empty?

echo "a b c d" | read X Y Z V
echo $X

I thought it would be a.

like image 626
Vojta Rylko Avatar asked Dec 04 '22 12:12

Vojta Rylko


2 Answers

The issue is that, in order to run the read command with its input redirected from the echo, a new subshell process is spawned. This process reads the values, assigns them to the variables - and then exits; then the second echo command is run. To demonstrate this you can do the second echo and the read both from a subshell:

$ echo "a b c d" | ( read X Y Z V; echo $X )
a
like image 158
psmears Avatar answered Dec 11 '22 15:12

psmears


In Bash, you can do a couple of different things to accomplish that:

A here string:

read X Y Z V <<< $(echo "a b c d"); echo $X

Process substitution:

read X Y Z V < <(echo "a b c d"); echo $X

A here document with command substitution:

read X Y Z V <<EOF
$(echo "a b c d")
EOF
echo $X

The here document method will also work with POSIX shells in addition to Bash.

If you're reading from a file instead of from the output of another command, it's a little simpler.

like image 27
Dennis Williamson Avatar answered Dec 11 '22 15:12

Dennis Williamson