Bash "inline" conventions

My goal is to add an argument to the executable if there is a bash variable like this:

bob -a some_arg (( if we have ${VAR} defined add '-b ${VAR}' as an argument ))

I would like to avoid something like:

if [[ -z ${VAR} ]]; then
    bob -a some_arg
else
    bob -a some_arg -b ${VAR}
fi

Although this is the only option?

+5
source share
2 answers

Using the bash extension:

bob -a some_arg ${VAR:+-b "$VAR"}

Some good docs: http://wiki.bash-hackers.org/syntax/pe

And LANG=C man bash | less +/'Parameter Expansion'

+9
source

You can use an array for this (see Arrays ):

args=( -a some_args )
if [ ... ] ; then
  args+=( -b "${VAR}" )
fi
bob "${args[@]}"
+2
source

All Articles