Skip to main content
Variable expansion allows you to retrieve and manipulate the value stored in a Bash variable using the $ syntax. This powerful feature is essential for automation, text processing, and script flexibility.

Introduction

In shell scripting, variables can store filenames, paths, numbers, or strings. By applying parameter expansion, you can:
  • Access variable contents
  • Perform string operations
  • Provide fallback values
  • Calculate lengths and more

Basic Variable Expansion

Whenever the shell sees $variable_name, it replaces it with the variable’s value:
Using braces helps delimit variable names clearly:
Variable names are case-sensitive and may contain letters, digits, and underscores:

Using Curly Braces

Curly braces {} not only disambiguate names but also unlock advanced parameter expansion features.

Avoiding Ambiguity

Without braces, attached text can be misinterpreted:

Default Values

Provide a fallback when a variable is unset or empty:
Use ${var:-default} to safely reference a variable that may not exist.

Parameter Expansion Operators

String Manipulation

Substring Extraction

Pull out part of a string using an offset and length:

Substring Replacement

Replace the first occurrence of a pattern:

Length of a Variable

Determine the number of characters in a variable’s value:

Quoting and Word Splitting

By default, unquoted expansions undergo word splitting. To preserve spaces, quote your variables. If you want to iterate over words, leave them unquoted:
Always quote expansions containing spaces unless you explicitly need word splitting.

Additional Resources

Watch Video