bash

How to add default array parameter to bash script


I am trying to pass an array of strings to my bash script that I want to iterate over. I want to set a default array in case the user does not provide this argument to the script.

This is what I have tried:

test.sh:

default_dirs=("x" "y")
dirs=("${1[@]:-${default_dirs[@]}}")
for directory in "${dirs[@]}"
do
    echo "$directory"
done

but running ./test.sh or

./test.sh "w" "z" yields:

./test.sh: line 2: ${1[@]:-${default_dirs[@]}}: bad substitution

What should I do differently?


Solution

  • The arguments to the script don't all come in $1 (and $1 isn't an array which is why the substitution fails), so use $@ instead:

    dirs=("${@:-${default_dirs[@]}}")
    for directory in "${dirs[@]}"
    do
        echo "$directory"
    done