variable expansion in curly braces

11,529

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.

Share:
11,529

Related videos on Youtube

user1929290
Author by

user1929290

Updated on September 15, 2022

Comments

  • user1929290
    user1929290 over 1 year

    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.