Why is the output empty?
echo "a b c d" | read X Y Z V
echo $X
I thought it would be a
.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With