Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable expansion in curly braces

Tags:

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.

like image 936
user1929290 Avatar asked Jan 04 '13 06:01

user1929290


People also ask

What are {} used for in Bash?

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 "{}".

What does curly braces mean in programming?

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.

Why curly braces are used in shell script?

The curly braces tell the shell interpreter where the end of the variable name is.

What is the difference between curly braces and curly brackets?

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.


1 Answers

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.

like image 105
Jonathan Leffler Avatar answered Oct 01 '22 12:10

Jonathan Leffler