Shell Variables
Curly Braces
Programming
Coding Practices
Script Writing

When do we need curly braces around shell variables?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

When working with shell scripting, particularly in environments like bash or sh, knowing when to use curly braces ({}) around variables can enhance script functionality, maintainability, and readability. This article explores the circumstances and advantages of using curly braces in shell scripting.

Purpose of Curly Braces in Shell Variables

Curly braces in shell scripting are used for explicit variable boundaries, string manipulation, and to prevent ambiguity. They enable the shell to clearly distinguish a variable from surrounding text, especially when a variable’s name is concatenated directly with other characters or strings.

When to Use Curly Braces

1. Disambiguating Variable Names

Variables in shell scripts are referenced by prefixing the variable name with a dollar sign ($). In cases where the variable is concatenated directly with other text or another variable, curly braces help in distinguishing the variable name from the adjoining text.

Example:

bash
username="donny"
echo "Username: $username123"  # Incorrect: This looks for a variable named 'username123'
echo "Username: ${username}123" # Correct: This clearly separates 'username' from '123'

2. String Manipulation

Curly braces are used for various forms of parameter expansion that allow string manipulation directly within a variable reference.

Examples:

  • Substring Extraction:
bash
  greeting="Hello, World!"
  echo ${greeting:7:5}  # Outputs 'World'
  • Default Values:
bash
  echo ${username:-"default_user"}  # Uses 'default_user' if 'username' is undefined or empty
  • String Replacement:
bash
  path="/usr/local/bin"
  echo ${path/bin/sbin}  # Outputs '/usr/local/sbin'

3. Creating Variable Names Dynamically

Sometimes, it's necessary to dynamically construct the names of variables. Curly braces can be used in such scenarios often combined with indirect expansion.

Example:

bash
1for i in 1 2 3
2do
3  varname="value$i"
4  declare "value$i"=$i
5  echo ${!varname} # Indirect expansion
6done

4. Complex Expressions Involving Variables

Curly braces are sometimes necessary when an expression involving a variable needs to be expanded before another operation is performed.

Example:

bash
filename="picture.png"
prefix="archived_"
echo ${prefix}${filename}  # Outputs 'archived_picture.png'

When Curly Braces Are Optional

In many simple uses, such as directly echoing or reading a standalone variable, braces are not necessary.

Example Without Braces:

bash
username="donny"
echo $username

Summary Table

UsageExample UsageWith Curly BracesWithout Curly BracesNotes
Plain variable outputecho ...echo ${var}echo $varBraces optional if not ambiguous
ConcatenationBuilding file pathsfile=${dir}/${name}-Braces needed to clarify boundary
String manipulationDefault values, substringecho ${name:0:4}-Necessary for the operation
Dynamic Variable NamingIndirect referencingecho ${!varname}-Required for indirect expansion
Expressions & CalculationsArithmetic operationsresult=${val1}+${val2}-Helps separate variables clearly

Conclusion

Using curly braces around shell variables can improve clarity, prevent errors, and enable advanced string manipulations. While they are not always necessary, using them consistently can help in creating more readable and maintainable scripts. Understanding when and how to use these braces within your scripting practices equips you with the precision and flexibility needed to master shell scripting tasks.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.