How do I pass an array as a variable from a first bash shell script to a second script.
first.sh
#!/bin/bash
AR=('foo' 'bar' 'baz' 'bat')
sh second.sh "$AR" # foo
sh second.sh "${AR[@]}" # foo
second.sh
#!/bin/bash
ARR=$1
echo ${ARR[@]}
In both cases, the result is foo
. But the result I want is foo bar baz bat
.
What am I doing wrong and how do I fix it?
Best Answer
AFAIK, you can't. You have to serialize it and deserialize it, e.g. via the argument array:
first
second
A little bit of advice:
export
ed variables"${someArray[@]}"
should always be double quoted; this formula behaves exactly like'array item 0' 'array item 1' 'aray item 2' 'etc.'
(assumingsomeArray=( 'array item 0' 'aray item 1' 'aray item 2' 'etc.' )
)