I'd like to use the read command for initialize a variable with a value which comes from the output of a previous command. I would expect that this works:
echo some_text | read VAR
But $VAR is empty. "read reads a single line from standard input." says the manpage. The pipeline sends the output of echo to the input of read. Where am I wrong?
My working solution is
echo text > file ; read VAR < file
But it uses a file...
I assume your shell is bash. When there is a pipeline, each command in the pipeline is executed in a subshell, and the parent shell connects all the appropriate file descriptors. So, the read command takes its stdin and sets the VAR variable, and then its subshell exits taking with it the variable.
You can use a here-doc
read VAR << END
text
END
Or, in bash, a here-string
read VAR <<< "text"
Or process substitution
read VAR < <(echo text)
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