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

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

return_an_array()
{
    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

Saturday, October 3, 2009

Determine if a Bash script was Executed or Sourced

[ "$0" == "$BASH_SOURCE" ] && echo 'executed' || echo 'sourced'