Bash : command line with optional arguments
tar -czf backup.tgz "$exclude1" "$exclude2" ${exclude3+"$exclude3"} 2>&1
${exclude3+"$exclude3"}
expands to nothing, if $exclude3
is unset, and to "$exclude3"
, if it is set.
(and similarly for the other variables that are potentially unset.)
Note that there is a difference between an unset variable and a variable that is set to the empty string, so you should use
unset exclude3
instead of
exclude3=''
Since you're working in bash, use an array.
excludes=()
excludes+=('--exclude=/path/*')
…
tar -czf backup.tgz "${excludes[@]}"
If you have an optional entry in some variable, add it in a conditional.
if [[ -n $exclude_or_empty ]]; then excludes+=("$exclude_or_empty"); fi