bashparameter-expansionpositional-parameter

What is the meaning of opts=${1:+--host $1} in bash?


In a bash script, I stumbled upon this piece of code:

opts=${1:+--host $1}
/path/somecmd $opts somesubcmd

By testing, I found out that $opts expands to --host $1 whatever $1 is.
I wonder what is the purpose of this syntax. Why not simply use opts="--host $1" ?

Is it a specific way to pass options to a command ?


Solution

  • As the bash manual says:

    ${parameter:+word}

    If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.

    When the bash manual says "parameter", it means "variable". When it says "null", it means "the empty string".

    In other words, ${foo:+bar} works like bar, but only if $foo is not empty.

    In your case,

    ${1:+--host $1}
    

    it checks $1. If $1 is unset or empty, the whole construct expands to nothing.

    Otherwise it expands to --host $1, as you have observed.