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

Attila Zobolyak
  • 739
  • 2
  • 10
  • 15
  • 1
    possible duplicate of [Bash script, read values from stdin pipe](http://stackoverflow.com/questions/2746553/bash-script-read-values-from-stdin-pipe) – glenn jackman Oct 26 '11 at 14:39

2 Answers2

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)
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
1

How about VAR=$( command ); ?

sr_
  • 547
  • 5
  • 14
  • [Like this?](http://stackoverflow.com/questions/2746553/bash-script-read-values-from-stdin-pipe/6779351#6779351) – sr_ Oct 26 '11 at 13:54