Can anyone explain this behavior? Running:
#!/bin/sh
echo \"hello world\" | read var1 var2
echo $var1
echo $var2
results in nothing being o
Try:
echo "hello world" | (read var1 var2 ; echo $var1 ; echo $var2 )
The problem, as multiple people have stated, is that var1 and var2 are created in a subshell environment that is destroyed when that subshell exits. The above avoids destroying the subshell until the result has been echo'd. Another solution is:
result=`echo "hello world"`
read var1 var2 <<EOF
$result
EOF
echo $var1
echo $var2
The post has been properly answered, but I would like to offer an alternative one liner that perhaps could be of some use.
For assigning space separated values from echo (or stdout for that matter) to shell variables, you could consider using shell arrays:
$ var=( $( echo 'hello world' ) )
$ echo ${var[0]}
hello
$ echo ${var[1]}
world
In this example var is an array and the contents can be accessed using the construct ${var[index]}, where index is the array index (starts with 0).
That way you can have as many parameters as you want assigned to the relevant array index.
My take on this issue (using Bash):
read var1 var2 <<< "hello world"
echo $var1 $var2