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
  • 98,580
  • 191
  • 570
  • 977
  • 1
    Exactly in those situations? – Jeff Schaller Jul 24 '17 at 19:35
  • 4
    [Do you ever use google ?](http://wiki.bash-hackers.org/syntax/pe#use_an_alternate_value) – don_crissti Jul 24 '17 at 19:55
  • ...see also Mike's and Stéphane's answers to [How do I check if a variable exists in an 'if' statement?](https://unix.stackexchange.com/q/212183) – don_crissti Jul 24 '17 at 20:06
  • See https://unix.stackexchange.com/a/286350/7696 - `${variable:+"$variable"}` is a useful way of quoting `$variable` without getting an empty string if it happens to be empty. – cas Jul 25 '17 at 02:04

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
  • 133,243
  • 15
  • 236
  • 397