Dinesh
Dinesh

Reputation: 4559

bash parameter expansion ${parameter:-SUB} vs ${parameter-SUB}

I see some bash scripts (on GNU bash, version 3.2.51(1)) with a parameter substitution like

function foo() {
  local x=${1-XYZ} ##### (1) 
  echo "x=${x}."
}
foo ####### this prints x=XYZ
foo ABCD ###### this prints x=ABCD

More commonly I see at (1) x=${1:-XYZ} and I can find it also described in the Bash reference pages here. Are both correct, or is something else also happening in the background and it might fail in some circumstances?

It does not have to be $1 - so long as the variable in ${XX-sub} is not defined, it picks the substitute. Thanks a lot

Upvotes: 0

Views: 161

Answers (3)

AkihikoTakahashi
AkihikoTakahashi

Reputation: 159

${var-word} returns "word" if var is undefined. If not, returns ${var}. ${var:-word} returns "word" if var is null or undefined. If not, returns ${var}.

You can easily check the difference with this sample script.

#!/bin/bash
var1=""  ## var1 is Null
#var2=   ## var2 is undefined
var3="value3"  ## var3 is set

echo '${var1}': ${var1} "(NULL)"
echo '${var2}': ${var2} "(Undefined)"
echo '${var3}': ${var3}

echo '${var1-foo}': ${var1-foo}
echo '${var2-foo}': ${var2-foo}
echo '${var3-foo}': ${var3-foo}

echo '${var1:-foo}': ${var1:-foo}
echo '${var2:-foo}': ${var2:-foo}
echo '${var3:-foo}': ${var3:-foo}

This script outputs.

${var1}: (NULL)
${var2}: (Undefined)
${var3}: value3
${var1-foo}:
${var2-foo}: foo
${var3-foo}: value3
${var1:-foo}: foo
${var2:-foo}: foo
${var3:-foo}: value3

Upvotes: 0

Gordon Davisson
Gordon Davisson

Reputation: 125928

The difference is that - uses the alternate value if the parameter is unset (i.e. not defined), and :- uses it is unset OR null (i.e. set to the empty string). For example:

$ foo() {
> echo "Argument 1 with :- is '${1:-altval}', with just - is '${1-altval}'"
> echo "Argument 2 with :- is '${2:-altval}', with just - is '${2-altval}'"
> }
$ foo ""
Argument 1 with :- is 'altval', with just - is ''
Argument 2 with :- is 'altval', with just - is 'altval'

Here I passed one (empty) argument to the function, so $1 was set to null, but $2 was unset.

Upvotes: 2

David C. Rankin
David C. Rankin

Reputation: 84579

If value is not set, use default, otherwise, use value:

var=${value-$default}
var=${value:-$default}   # ':' use default even if value declared and empty/null

e.g (missing command line parameters):

value=
var=${value-$default}     # not set
var=${value:-$default}    # set to $default

Upvotes: 2

Related Questions