Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am essentially trying to assing certain portions of the output of a shell command to mulitple variables, but I don't know how to do that.

For simplicity's sake, assume that the command on the shell, when executes, prints

one two three four

which can be simulated with a

echo "one two three four"

(although the actual comannd is different)

Now, I'd like to assign the second and fourth word of the output (in this case two and four) to the variables w1 and w2.

I thought I could use the read command like so:

echo "one two three four" | awk '{print $2 " " $4}' | read w1 w2

but this doesn't work, probably because the read command is executed in a sub-process.

So, how would I go about to achieve what I am after?

share|improve this question
up vote 14 down vote accepted

This doesn't work because the read runs in a child process which cannot affect the parent's environment.

You have a few options:

You can convert your command to:

w1=$(echo "one two three four" | awk '{print $2}')
w2=$(echo "one two three four" | awk '{print $4}')

Alternatively, change IFS and use set:

IFS=' '
set -- $(echo "one two three four" | awk '{print $2" "$4}')
w1=$1 w2=$2

or a Here String:

read w1 w2 w3 w4 <<< "one two three four"
share|improve this answer
Based on the Here String: read a1 a2 a3 <<< $(echo one two three) – Petr Uzel Apr 11 '11 at 9:45
Thanks a lot. I didn't know about the <<< Here String – René Nyffenegger Apr 11 '11 at 10:26

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.