1

From Bash manual

${parameter:+word}

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

It looks like string replacement only when the target string in "parameter" exists and is not null.

What are the purpose and use cases of this kind of parameter expansion?

Thanks.

Tim
  • 101,790

1 Answers1

2

You could use that with a flag variable to e.g. add some flag to a command line:

use_x=1
param_x=foobar
somecmd ${use_x:+-x} ${use_x:+$param_x}

Of course, the part with param_x isn't such a good idea, with it being subject to word-splitting and globbing. That shouldn't be a problem for the static flag itself, though, but in general, using an array here would be more robust.

To test if the variable is set, [ -n "$var" ] works similarly, so there's not much use for ${var:+value}. On the other hand, ${var+value} (without the colon) is useful to tell the difference between an empty and an unset variable:

unset a
b=
[ "${a+x}" = "x" ] && echo a is set
[ "${b+x}" = "x" ] && echo b is set
ilkkachu
  • 138,973