I have been trying to return a bash array from a bash function into a variable. However, no matter what I do, if any of the element contains whitespaces then things are going south. I suspect the problem is the way I have been storing the function output to the variable(my_arr=($(my_function))
. A similar question is asked here but it didn't work for my usecase.
Here is a sample function:
my_function()
{
my_arr=("random dude" EU 10 "boss" US 20)
echo "${my_arr[@]}"
}
my_arr=($(my_function))
#printing individual elements of the array, Here only things started to mess up
# zeroth element is printed as 'random' not 'random dude'
echo "zeroth: ${my_arr[0]}"
echo "first: ${my_arr[1]}"
echo "second: ${my_arr[2]}"
echo "third: ${my_arr[3]}"
echo "forth: ${my_arr[4]}"
echo "fifth: ${my_arr[5]}"
#so any attempt of looping is irrelavent
echo "----Attempt-1-------"
for elem in "${my_arr[@]}"; do
echo "${elem}";
done
echo "---Attempt-2--------"
for elem in $(printf "%q " "${my_arr[@]}") ;do
echo "$elem"
done
Current output:
zeroth: random
first: dude
second: EU
third: 10
forth: boss
fifth: US
I was expecting:
zeroth: random dude
first: EU
second: 10
third: boss
forth: US
fifth: 20
Is there a way I can reliably store the array returned/printed by function outside of the function? I am on a legacy system where I do not have access to python
, its a bash (with tools like awk, sed, etc) and perl only environment.