Attila Zobolyak
Attila Zobolyak

Reputation: 749

redirecting input for read command in UNIX

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

Upvotes: 4

Views: 3566

Answers (2)

glenn jackman
glenn jackman

Reputation: 246754

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)

Upvotes: 8

sr_
sr_

Reputation: 602

How about VAR=$( command ); ?

Upvotes: 1

Related Questions