0

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 ?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
LuoLeKe
  • 95
  • 1
  • 8
  • [Here](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html) is a good reference about what all those `${...}` do – Aaron Jun 14 '19 at 13:33

3 Answers3

0

It prepends --host to the first parameter due to the +, but only if $1 isn't empty.

$ function mytest { echo ${1:+--host $1}; }
$ mytest ls
--host ls
$ mytest ""

Equivalent would be:

$ function mytest { [ -z "$1"] || echo --host $1; }
$ mytest ls
--host ls

There's a lot to read about shell parameter expansion.

Bayou
  • 3,293
  • 1
  • 9
  • 22
0

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.

Community
  • 1
  • 1
melpomene
  • 84,125
  • 8
  • 85
  • 148
0

The parameter expansion ${variable:+value} produces value if variable is nonempty, and nothing otherwise. So this is a way to say "add --host $1 if $1 is set." (The expansion should properly quote the string; ${1:+--host "$1~})

tripleee
  • 175,061
  • 34
  • 275
  • 318