BASH: Passing values from function to array

Tuesday, August 19, 2008

This has always been something that sort of irks me from time to time. Sure, you can pass values to an array as follows:

biteme() {
x=abc
y=123
echo $x $y
}

array=($(biteme))
echo "Element 0 is ${array[0]}, element 1 is ${array[1]}"

And you would get:

Element 0 is abc, element 1 is 123

But what if the value had a space in it? For example, change x in function biteme to abc def, and you would get:

Element 0 is abc, element 1 is def

Instead. I've always gotten around this by setting IFS to something else, say colon...then reset IFS after the function is called. For example:

biteme() {
x=abc
y=123
sp=":"
echo $x$sp$y
}

OFS=IFS;IFS=":";array=($(biteme));IFS=OFS
echo "Element 0 is ${array[0]}, element 1 is ${array[1]}"

Obviously this isn't very elegant...but it works...its either IFS or parse it through a for loop and manually assign each element in the array...if there's another way to do this I'm all ears.

0 Comments: