user1929290
user1929290

Reputation: 295

variable expansion in curly braces

This is code

a=''
b=john
c=${a-$b}
echo $c

And the output is empty line

And for similar code where first variable is not initialized

b1=doe
c1=${a1-$b1}
echo $c1

And the output is

doe

I do not understand how bash deals with expanding of variables leading to different results.

Upvotes: 27

Views: 15751

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753475

There are two variants of the ${var-value} notation, one without a colon, as shown, and one with a colon: ${var:-value}.

The first version, without colon, means 'if $var is set to any value (including an empty string), use it; otherwise, use value instead'.

The second version, with colon, means 'if $var is set to any value except the empty string, use it; otherwise, use value instead'.

This pattern holds for other variable substitutions too, notably:

  • ${var:=value}
    • if $var is set to any non-empty string, leave it unchanged; otherwise, set $var to value.
  • ${var=value}
    • if $var is set to any value (including an empty string), leave it unchanged; otherwise, set $var to value.
  • ${var:?message}
    • if $var is set to any non-empty string, do nothing; otherwise, complain using the given message' (where a default message is supplied if message is itself empty).
  • ${var?message}
    • if $var is set to any value (including an empty string), do nothing; otherwise, complain using the given message'.

These notations all apply to any POSIX-compatible shell (Bourne, Korn, Bash, and others). You can find the manual for the bash version online — in the section Shell Parameter Expansion. Bash also has a number of non-standard notations, many of which are extremely useful but not necessarily shared with other shells.

Upvotes: 63

Related Questions