How to pass an array argument to the Bash script How to pass an array argument to the Bash script bash bash

How to pass an array argument to the Bash script


Bash arrays are not "first class values" -- you can't pass them around like one "thing".

Assuming test.sh is a bash script, I would do

#!/bin/basharg1=$1; shiftarray=( "$@" )last_idx=$(( ${#array[@]} - 1 ))arg2=${array[$last_idx]}unset array[$last_idx]echo "arg1=$arg1"echo "arg2=$arg2"echo "array contains:"printf "%s\n" "${array[@]}"

And invoke it like

test.sh argument1 "${array[@]}" argument2


Have your script arrArg.sh like this:

#!/bin/basharg1="$1"arg2=("${!2}")arg3="$3"arg4=("${!4}")echo "arg1=$arg1"echo "arg2 array=${arg2[@]}"echo "arg2 #elem=${#arg2[@]}"echo "arg3=$arg3"echo "arg4 array=${arg4[@]}"echo "arg4 #elem=${#arg4[@]}"

Now setup your arrays like this in a shell:

arr=(ab 'x y' 123)arr2=(a1 'a a' bb cc 'it is one')

And pass arguments like this:

. ./arrArg.sh "foo" "arr[@]" "bar" "arr2[@]"

Above script will print:

arg1=fooarg2 array=ab x y 123arg2 #elem=3arg3=bararg4 array=a1 a a bb cc it is onearg4 #elem=5

Note: It might appear weird that I am executing script using . ./script syntax. Note that this is for executing commands of the script in the current shell environment.

Q. Why current shell environment and why not a sub shell?
A. Because bash doesn't export array variables to child processes as documented here by bash author himself


You can write your array to a file, then source the file in your script.e.g.:

array.sh

array=(a b c)

test.sh

source $2...

Run the test.sh script:

./test.sh argument1 array.sh argument3