18

I have a bash script that uses the following syntax:

if [ ! -z ${ARGUMENT+x} ]; then

What is the meaning of the "+x" syntax after the argument name?

codeforester
  • 34,080
  • 14
  • 96
  • 122
Alessandro C
  • 3,070
  • 6
  • 36
  • 74
  • @Benjamin W. Yes, it's the same question, but I didn't found it because it's intended for "plus colon". That was not my issue. My issue was about arguments, not "plus colon". – Alessandro C Oct 23 '17 at 15:04
  • Both questions are about parameter expansion with `+`; it doesn't matter what comes after the `+`, so in my opinion, they are duplicates. – Benjamin W. Oct 23 '17 at 15:07
  • 2
    Ok. But anyway I didn't found that question, so it means that everyone is looking for "argument" with "+x" will never find that question, they will find my question. – Alessandro C Oct 23 '17 at 17:10
  • 1
    That's fine - it's now a signpost pointing to the other question. – Benjamin W. Oct 23 '17 at 17:51
  • Using `[ ! -z "…" ]` is a long-winded and devious/obscure way of writing `[ -n "…" ]`. The first checks for not zero length, but so does the second, without the additional operator. – Jonathan Leffler Jan 15 '21 at 06:10

2 Answers2

23

It means that if $ARGUMENT is set, it will be replaced by the string x

Let's try in a shell :

$ echo  ${ARGUMENT+x}

$ ARGUMENT=123
$ echo  ${ARGUMENT+x}
x

You can write this with this form too :

${ARGUMENT:+x}

It have a special meaning with :, it test that variable is empty or unset

Check bash parameter expansion

Gilles Quenot
  • 154,891
  • 35
  • 213
  • 206
12

Rather than discussing the syntax, I'll point out what it is attempting to do: it is trying to deterimine if a variable ARGUMENT is set to any value (empty or non-empty) or not. In bash 4.3 or later, one would use the -v operator instead:

if [[ -v ARGUMENT ]]; then
chepner
  • 446,329
  • 63
  • 468
  • 610
  • Ah ok, so this is equivalent. Nice to know. In effect that was a pretty old script, but I didn't know the syntax. – Alessandro C Oct 23 '17 at 15:05
  • In isolation, these are equivalent, but you can use `${var+x}` anywhere you can use `$var` so it can be part of a more complex expression, perhaps involving multiple variables etc. – tripleee Oct 23 '17 at 15:18
  • Note that "modern `bash`" here specifically means version `>=4.3`. – boweeb Sep 27 '21 at 19:22
  • Yeah, saying "modern" instead of providing a specific version was a dumb idea. – chepner Sep 27 '21 at 20:42