4

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

1

2 Answers 2

8

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) 
Sign up to request clarification or add additional context in comments.

Comments

1

How about VAR=$( command ); ?

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.