Linux bash: Multiple variable assignment

GetFree picture GetFree · Dec 23, 2009 · Viewed 131.4k times · Source

Does exist in linux bash something similar to the following code in PHP:

list($var1, $var2, $var3) = function_that_returns_a_three_element_array() ;

i.e. you assign in one sentence a corresponding value to 3 different variables.

Let's say I have the bash function myBashFuntion that writes to stdout the string "qwert asdfg zxcvb". Is it possible to do something like:

(var1 var2 var3) = ( `myBashFuntion param1 param2` )

The part at the left of the equal sign is not valid syntax of course. I'm just trying to explain what I'm asking for.

What does work, though, is the following:

array = ( `myBashFuntion param1 param2` )
echo ${array[0]} ${array[1]} ${array[2]}

But an indexed array is not as descriptive as plain variable names.
However, I could just do:

var1 = ${array[0]} ; var2 = ${array[1]} ; var3 = ${array[2]}

But those are 3 more statements that I'd prefer to avoid.

I'm just looking for a shortcut syntax. Is it possible?

Answer

Michael Krelin - hacker picture Michael Krelin - hacker · Dec 23, 2009

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