Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirecting input for read command in UNIX

Tags:

shell

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...

like image 916
Attila Zobolyak Avatar asked Jan 19 '23 10:01

Attila Zobolyak


1 Answers

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)
like image 163
glenn jackman Avatar answered Jan 21 '23 01:01

glenn jackman