Why does the following work from the prompt but fail when stuck inside a bash script? The bash script produces one empty line leading me to believe the variable isn't being set:

echo "red sox" | read my_var
echo $my_var

UPDATE: Since I guess my example isn't working, what I'm really trying to do is take I/O and pipe it into a variable to so I can do things with it. How do I do this? I thought this should be taken care of by the read command, but maybe there's another way?

+1  A: 

It doesn't work at the prompt. My guess is you already have my_var set in your CLI, and are just retrieving that at the prompt.

Try this:

$ my_var="nothing"; echo "red sox" | read my_var; echo $my_var


If you want the my_var variable to have a constant value, as in your question, why not just do:

my_var="red sox"
Richard Fearn
+4  A: 

If you are asking this because you simplified from a more general problem such as:

someprog args | read my_var

you should be using command substitution:

my_var=$(someprog args)
R Samuel Klatchko
+2  A: 

You can store the output of a command in a variable using either backticks or $() syntax:

my_var=`cat /some/file.txt`

Now the content of /some/file.txt is stored in $my_var. Same thing, with different syntax:

my_var=$(cat /some/file.txt)
Peter Lyons

Are you trying to pass args on the command line?

If so, $0 will contain the script name, and $1..n will contain command line args.

$@ will contain all command line args, space-separated.


What are you trying to do? Please explain what you wan't to do first.

If you're trying to set a variable this is what you need:

my_var="red sox"
echo $my_var

If you need it globally you should set it in env:

export my_var
Andreas Rehm

The reason read doesn't work in a pipe the way you have it is that it creates a subshell. Variables set in a subshell don't persist to their parents. See BashFAQ/024.

Dennis Williamson