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/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

Leave a Comment