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?
(( ${#dirs[@]} )) || dirs=("${default_dirs[@]}")is one way.dirs=("${dirs[@]:-"${default_dirs[@]}"}")might be what you wanted../test.sh w zinvokes the script not with one array parameter, but with two parameters (w and z). It is just that inside the script, you can alternatively access all parameters passed via the special array named@. Note however, that@does not behave in every respect like a bash array.