23

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
  • 39,467
  • 16
  • 112
  • 140
Alessandro C
  • 3,310
  • 9
  • 46
  • 82
  • @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
  • 3
    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

27

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 Quénot
  • 173,512
  • 41
  • 224
  • 223
14

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
  • 497,756
  • 71
  • 530
  • 681
  • 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
  • 1
    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