linuxbashshellvariable-assignmentmultiple-variable-return

Linux bash: Multiple variable assignment


Does there 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 myBashFunction that writes to stdout the string qwert asdfg zxcvb. Is it possible to do something like:

(var1 var2 var3)=(`myBashFunction 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=(`myBashFunction 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?


Solution

  • 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