Bee..
Bee..

Reputation: 195

Explain ${var:-val} and ${var+val}

Can any one explain this format?

${name:-$devi}

Example:

      "${1+"$@"}" will check for that first variable to be set , if not it will use that 

        command line argument. 

What is the difference between :- and + between those variables?

Upvotes: 2

Views: 567

Answers (1)

Barmar
Barmar

Reputation: 781716

${var:-val}

is the same as ${var} if var is set and non-null, otherwise it expands to val. This is used to specify a default value for a variable.

${var+val}

expands to nothing if var is unset, otherwise it expands to val. This is used to supply an alternate value for a variable.

"${1+"$@"}"

is a workaround for a bug in old shell versions. If you just wrote "$@", it would expand to "" when no arguments were supplied, instead of expanding to nothing; the script would then act as if a single, empty argument had been supplied. This syntax first checks whether $1 is set -- if there's no first argument, then there are obviously no arguments at all. If $1 is unset, it expands to nothing, otherwise it's safe to use "$@".

Most modern shell versions don't have this bug, so you can just write "$@" without the special check. I'm not sure if there are any other common use cases for the + construct in shell variable expansion.

Upvotes: 1

Related Questions