How to pass an array argument to the Bash script

Solution 1:

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/bash
arg1=$1; shift
array=( "$@" )
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

Solution 2:

Have your script arrArg.sh like this:

#!/bin/bash

arg1="$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=foo
arg2 array=ab x y 123
arg2 #elem=3
arg3=bar
arg4 array=a1 a a bb cc it is one
arg4 #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

Solution 3:

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