I am trying to write a simple function in bash which takes 2 arguments, a string and an array.
At the very beggining of the function I check for the number of arguments
function is2args() {
if [ $# -le 1 ]; then
return 1
fi
return 0
}
I then attempt the following
arr=()
is2args "" "${arr[@]}" # returns 1
This triggers the if statement as bash for some reason thinks there is only one argument however if the list is an empty string it works
arr=()
is2args "" "" # returns 0
or filled with elements
arr=(
"element"
)
is2args "" "${arr[@]}" # returns 0
and default to an empty string
arr=()
is2args "" "${arr[@]:-""}" # returns 0
I don't quite understand what is going on. It is my understanding this is the correct way to pass a list however it seems that an empty list is ignored for whatever reason.
Should I really be setting a default empty string every time I send through an array or is there a way to catch this in the function itself?