views:

282

answers:

3

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?

+4  A: 

First thing that comes into my mind:

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

output is, unsurprisingly

1|2|3
Michael Krelin - hacker
How come I didn't think of this before. Thanks
GetFree
A: 

Chapter 5 of the Bash Cookbook by O'Reilly, discusses (at some length) the reasons for the requirement in a variable assignment that there be no spaces around the '=' sign

MYVAR="something"

The explanation has something to do with distinguishing between the name of a command and a variable (where '=' may be a valid argument).

This all seems a little like justifying after the event, but in any case there is no mention of a method of assigning to a list of variables.

pavium
Yes, I know. I just added extra spaces here and there for the sake of readability
GetFree
Yes, that's true: readbiity really suffers in bash scripts.
pavium
A: 

I think this might help...

In order to break down user inputted dates (mm/dd/yyyy) in my scripts, I store the day, month, and year into an array, and then put the values into separate variables as follows:

DATE_ARRAY=(`echo $2 | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)
SDGuero