I have bash script with set -o nounset
option (and I want that!).
Now, I want construct a command invocation, but I don't know number of arguments beforehand, so I want to use an array for that (example below). However, when ARRAY
is an empty array, "${ARRAY[@]}"
fails.
Question: how to @-expand array ("${ARRAY[@]}"
) so that the expansion does not fail when set -o nounset
is on?
Example:
# Clone git repo. Use --reference if ${reference_local_repo} exist.
reference_local_repo=.....
test -d "${reference_local_repo}" \
&& reference=("--reference" "${reference_local_repo}") \
|| reference=()
git clone "${reference[@]}" http://address/of/the/repo
Of course, I could use the following instead:
# bad example
reference=''
test -d "${reference_local_repo}" && reference="--reference ${reference_local_repo}"
... but that wouldn't work if the path to local repo contained a whitespace.
As a workaround, instead of reference=()
i use reference=("-c" "dummy.dummy=dummy")
. That way I avoid empty array, and Bash does not complain. Alternatively, i can (rename the array variable and) have "clone" as the first array element. So I got this working, but I'd like to learn The Proper Way.
For the record, I'm using GNU bash, version 4.3.42(1)-release (x86_64-pc-linux-gnu)
.