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.
Bash brace expansion is used to generate stings at the command line or in a shell script. The syntax for brace expansion consists of either a sequence specification or a comma separated list of items inside curly braces "{}".
Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.
The curly braces tell the shell interpreter where the end of the variable name is.
They're the same thing. As a UK speaker my feeling is that most Brits would refer to "brackets" whilst "braces" is more of a US usage.
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}
$var
is set to any non-empty string, leave it unchanged; otherwise, set $var
to value
.${var=value}
$var
is set to any value (including an empty string), leave it unchanged; otherwise, set $var
to value
.${var:?message}
$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}
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With