$ 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 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
| Expansion Type | Syntax | Description |
|---|---|---|
| Default Value | ${var:-default} | Use default if var is unset or null |
| Substring Extraction | ${var:offset:length} | Extract a substring starting at offset |
| String Replacement | ${var/pattern/repl} | Replace the first match of pattern with repl |
| Length | ${#var} | Return the length of var’s value |
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.