What are curly braces for?

0138

Curly braces {} in shell scripting are used for several purposes, primarily to clearly define variable names and to perform parameter expansion. Here are the main uses:

1. Defining Variable Names

When a variable is followed by additional characters, curly braces help to clearly delineate the variable name from the surrounding text. This is especially useful when concatenating strings.

Example:

name="Labby"
echo "Hello, ${name}123"

Output:

Hello, Labby123

Without curly braces, the shell would look for a variable named name123, which does not exist.

2. Parameter Expansion

Curly braces can be used for various forms of parameter expansion, such as:

  • Default Values: Assigning a default value if the variable is unset or null.

    Example:

    echo "Value: ${var:-default_value}"
  • Substring Extraction: Extracting a substring from a variable.

    Example:

    string="Hello, World!"
    echo "${string:7:5}"  # Outputs "World"

3. Array Access

In bash, curly braces are used to access elements of an array.

Example:

array=(one two three)
echo "${array[1]}"  # Outputs "two"

Summary

Curly braces are useful for clearly defining variable names, performing parameter expansions, and accessing array elements in shell scripts. They help avoid ambiguity and improve code readability.

0 Comments

no data
Be the first to share your comment!