2

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?

Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
  • 7
    See this http://stackoverflow.com/questions/16019389/passing-an-array-from-one-bash-script-to-another – ralf htp Apr 23 '16 at 07:44

2 Answers2

4

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.

jofel
  • 3,297
  • 17
  • 31
  • By convention, environment variables (`PATH`, `EDITOR`, `SHELL`, ...) and internal shell variables (`BASH_VERSION`, `RANDOM`, ...) are fully capitalized. All other variable names should be lowercase. Since variable names are case-sensitive, this convention avoids accidentally overriding environmental and internal variables. – Rany Albeg Wein Apr 23 '16 at 16:02
1

Try changing ARR=$1 in second.sh with ARR=("$@"). $1 assumes a single variable but you need to serialize all array items.

taras
  • 6,566
  • 10
  • 39
  • 50