0

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?

2
  • 4
    That doesn't work on my prompt. What are you trying to do? Commented Jun 30, 2010 at 20:27
  • 1
    Aye, doesn't work here either. If you already know the value "red sox" why not assign it directly to my_var? Commented Jun 30, 2010 at 20:32

6 Answers 6

5

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

Comments

3

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.

Comments

2

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)

Comments

1

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

Comments

0

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

my_var="red sox"

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.