πŸ“

Bash Parameter Expansion Overview

Jul 17, 2025

Overview

This lecture explains Bash parameter expansion, highlighting its syntax and practical uses for reading, modifying, and substituting variable values in shell scripts.

What is Bash Parameter Expansion?

  • Parameter expansion retrieves or modifies the value of a shell variable using ${variable} syntax.
  • Curly brackets {} are used for complex expansions, especially when modifying parameter values.

Parameter Expansion vs. Substitution

  • Parameter expansion allows setting default values if variables are undefined; substitution only retrieves values without defaults.
  • Example: ${language:-Bash} prints "Bash" if language is unset; ${language} prints the set value.

Conditional Parameter Expansion

  • ${var:-default} prints the default if var is unset or empty, but does not assign it.
  • ${var:+alt} prints alt if var is set, otherwise prints nothing.
  • ${var:=default} prints and assigns default if var is unset or empty.

Substring Operations

  • ${var:offset:length} extracts part of a string; offset is start index, length is optional.
  • Example: ${var:0:4} gets the first four characters.

String Substitution

  • ${var/pattern/replacement} replaces the first match of pattern with replacement.
  • ${var//pattern/replacement} replaces all matches.

Regex and Removal

  • Use patterns like ${var/%pattern/replacement} to match and replace endings.
  • Example: Remove numbers at string’s end and append another value.

Splitting Strings

  • You can split strings on a delimiter into arrays using parameter expansion and loops.
  • Example: ${course//:/ } splits a colon-separated string into parts.

Cheat Sheet Highlights

  • Print variable: ${parameter}
  • Print with default: ${parameter:-default}
  • Assign default if unset: ${parameter:=default}
  • Alternate if set: ${parameter:+alt}
  • Length of var: ${#parameter}
  • Substring: ${parameter:offset:length}
  • Search/replace: ${parameter/search/replace} or ${parameter//search/replace}
  • Indirect reference: ${!parameter}

Key Terms & Definitions

  • Parameter Expansion β€” Method for retrieving or modifying variable values in Bash with ${} syntax.
  • Default Value β€” Value assigned or printed if variable is unset, using :- or :=.
  • Substring Extraction β€” Pulling part of a string using start index and optional length.
  • Substitution β€” Replacing part or all occurrences of a substring or pattern.
  • Indirection β€” Accessing the value of a variable whose name is stored in another variable with ${!parameter}.

Action Items / Next Steps

  • Practice writing scripts using different forms of parameter expansion.
  • Review and memorize the common expansion patterns from the cheat sheet.