Linux bash: Multiple variable assignment Linux bash: Multiple variable assignment bash bash

Linux bash: Multiple variable assignment


First thing that comes into my mind:

read -r a b c <<<$(echo 1 2 3) ; echo "$a|$b|$c"

output is, unsurprisingly

1|2|3


I wanted to assign the values to an array. So, extending Michael Krelin's approach, I did:

read a[{1..3}] <<< $(echo 2 4 6); echo "${a[1]}|${a[2]}|${a[3]}"

which yields:

2|4|6 

as expected.


Sometimes you have to do something funky. Let's say you want to read from a command (the date example by SDGuero for example) but you want to avoid multiple forks.

read month day year << DATE_COMMAND $(date "+%m %d %Y")DATE_COMMANDecho $month $day $year

You could also pipe into the read command, but then you'd have to use the variables within a subshell:

day=n/a; month=n/a; year=n/adate "+%d %m %Y" | { read day month year ; echo $day $month $year; }echo $day $month $year

results in...

13 08 2013n/a n/a n/a