How to pass array to bash shell script?

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.' ) )

The AR array is passed via the first argument to second.sh.

first.sh

#!/bin/bash
AR=('foo' 'bar' 'a space' 'bat')
printf "AR array contains %d elements: " ${#AR[@]}
printf "%s " "${AR[@]}"
printf "\n"
./second.sh "$AR"
./second.sh "$(printf "(" ; printf "'%s' " "${AR[@]}" ; printf ")")"

Note that sh is not used anymore to run the second.sh script.

These chained printf are used to forge a single parameter that will be safe if some array elements contain space chars.

second.sh

#!/bin/bash
declare -a ARR=$1
printf "ARR array contains %d elements: " ${#ARR[@]}
printf "%s " "${ARR[@]}"
printf "\n"

----

For a solution where the AR array is passed using any number of arguments to the second.sh script.

first.sh

#!/bin/bash
AR=('foo' 'bar' 'a space' 'bat')
printf "AR array contains %d elements: " ${#AR[@]}
printf "%s " "${AR[@]}"
printf "\n"
./second.sh "$AR"
./second.sh "${AR[@]}"

second.sh

#!/bin/bash
ARR=( "$@" )
printf "ARR array contains %d elements: " ${#ARR[@]}
printf "%s " "${ARR[@]}"
printf "\n"

----

The test:

$ chmod +x *sh
$ ./first.sh
AR array contains 4 elements: foo bar a space bat
ARR array contains 1 elements: foo
ARR array contains 4 elements: foo bar a space bat