Mowzer Mowzer - 7 months ago 14
Bash Question

How to pass array to bash shell script?

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?

Answer

Use

sh second.sh "${AR[@]}"

which split the array elements in different arguments, i.e

sh second.sh "${A[0]}" "${A[1]}" "${A[2]}" ...

and in second.sh use

ARR=("$@")

to collect the command line arguments into an array.

Comments