Alex Rivera | Logout

Exporting an array in bash script

Asked 2011-04-06T09:48:19.053
89

I can not export an array from a bash script to another bash script like this:

export myArray[0]="Hello"
export myArray[1]="World"

When I write like this there are no problem:

export myArray=("Hello" "World")

For several reasons I need to initialize my array into multiple lines. Do you have any solution?

Edit
Report

1 Answer

1

As lesmana reported, you cannot export arrays. So you have to serialize them before passing through the environment. This serialization useful other places too where only a string fits (su -c 'string', ssh host 'string'). The shortest code way to do this is to abuse 'getopt'

# preserve_array(arguments). return in _RET a string that can be expanded
# later to recreate positional arguments. They can be restored with:
#   eval set -- "$_RET"
preserve_array() {
    _RET=$(getopt --shell sh --options "" -- -- "$@") && _RET=${_RET# --}
}

# restore_array(name, payload)
restore_array() {
   local name="$1" payload="$2"
   eval set -- "$payload"
   eval "unset $name && $name=("\$@")"
}

Use it like this:

foo=("1: &&& - *" "2: two" "3: %# abc" )
preserve_array "${foo[@]}"
foo_stuffed=${_RET}
restore_array newfoo "$foo_stuffed"
for elem in "${newfoo[@]}"; do echo "$elem"; done

## output:
# 1: &&& - *
# 2: two
# 3: %# abc

This does not address unset/sparse arrays. You might be able to reduce the 2 'eval' calls in restore_array.

answered 2013-06-21T13:30:50.173

Your Answer