Tuesday, December 1, 2009

Return an Array from a Bash Function v. 2

I wrote an earlier post about returning an array from a Bash function. This version is better.

#! /bin/bash

# $ ./array_to_string.sh 'this' 'is a' 'test'
# declare -a output_array='([0]="this" [1]="is a" [2]="test")'
# declare -a output_array='([0]="this" [1]="is a" [2]="test")'

array_to_string()
{
    # Treat the arguments as an array:
    local -a array=( "$@" )
    declare -p array | sed -e 's/^declare -a array=//'
}

# Pass an array to a function:
input_array=( "$@" )
string="$(array_to_string "${input_array[@]}")"

# string_to_array idiom:
string_to_array_code="declare -a output_array=${string}"
eval "$string_to_array_code"

# The outputs of the following two commands should be identical:
echo "$string_to_array_code"
declare -p output_array
blog comments powered by Disqus