Sunday, October 4, 2009

Return an Array from a Bash Function

Update 2009/12/01: I recommend the newer solution I posted today instead of the one below.

The following safely handles array elements containing spaces.  Other solutions I've found do not.

#! /bin/bash

# $ ./ 
# ./ line 9: declare: returned_array: not found
# declare -a returned_array='([0]="one" [1]="two three")'

    local -a an_array=( 'one' 'two three' )
    declare -p an_array

declare -p returned_array
eval $(return_an_array | sed -e 's/^\(declare -a \)[^=]*=/\1 returned_array=/')
declare -p returned_array
blog comments powered by Disqus