Bash Shell Script – How to Pass Array

arraybashshellshell-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?

Best Answer

AFAIK, you can't. You have to serialize it and deserialize it, e.g. via the argument array:

first

#!/bin/bash
ar=('foo' 'bar' 'baz' 'bat')
second "${ar[@]}" #this is equivalent to: second foo bar baz bat

second

#!/bin/bash
arr=( "$@" )
printf ' ->%s\n' "${arr[@]}"
<<PRINTS
   -> foo
   -> bar
   -> baz
   -> bat
PRINTS

A little bit of advice:

  • reserve all caps for exported variables
  • unless you have a very good specific reason for not doing so "${someArray[@]}" should always be double quoted; this formula behaves exactly like 'array item 0' 'array item 1' 'aray item 2' 'etc.' (assuming someArray=( 'array item 0' 'aray item 1' 'aray item 2' 'etc.' ) )