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?


2 Answers 2


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"
  • 4
    Based on the Here String: read a1 a2 a3 <<< $(echo one two three)
    – Petr Uzel
    Apr 11, 2011 at 9:45
  • Thanks a lot. I didn't know about the <<< Here String Apr 11, 2011 at 10:26
  • 1
    For safety you should use: read -r: do not allow backslashes to escape any characters
    – Tom Hale
    Sep 17, 2017 at 8:54

The example get password 1 and 2 from the file password.txt


password1:password2:password3:column jnAKcxu7tyLa7DJa:nn53tSnuJJxmYbEN:97m8crLrF3ap9y9R:listpassword

Jenny:37 Joun:40

read pass1 pass2 <<< $(awk -F: '/listpassword/{ print $1,$2; }' password.txt)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .