๐ง Extended Parameters and Expansions
Beyond basic variable assignment (var=value), shells offer powerful mechanisms for manipulating parameters, performing substitutions, and handling missing values gracefully.
๐งญ Why Extended Expansions Matter
In production scripts, you'll frequently encounter: - Variables that might be unset - Strings that need transformation - Default values that should apply conditionally - Indirect references to variable names
Extended parameter expansions handle all these cases without external tools, making scripts faster and more portable.
๐งฎ Basic Parameter Expansion Recap
Before diving into advanced features, let's review the fundamentals:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
๐งช Default Values
Unset or Empty Variables
Provide fallback when variable doesn't exist or is empty:
1 2 3 | |
This is extremely useful for configuration:
1 2 3 4 5 6 7 8 | |
The : builtin is a no-op โ it's used here purely for the side effect of parameter expansion.
Assign Default Permanently
Use := to set the variable if it's unset:
1 2 | |
Subsequent uses will see the assigned value:
1 | |
Require Variable to Be Set
Fail fast if required variable is missing:
1 | |
If DATABASE_URL is unset or empty, the script exits with:
1 | |
This is perfect for mandatory configuration.
๐ง Pattern-Based Substitutions
Remove Prefix
Strip shortest matching prefix:
1 2 3 4 5 6 7 | |
Remove Suffix
Strip shortest matching suffix:
1 2 3 4 5 6 7 8 9 10 | |
๐งช Advanced Replacement Patterns
Case Modification
Convert case without external tools:
1 2 3 4 5 6 | |
โ ๏ธ Bash 4.0+ / Zsh only โ not POSIX.
Search and Replace
Replace patterns within strings:
1 2 3 4 5 6 7 8 9 | |
Useful for sanitizing paths or generating identifiers.
๐ง Indirect Variable References
Access a variable whose name is stored in another variable:
1 2 3 | |
Practical example โ configuration map:
1 2 3 4 5 6 7 8 9 | |
Output:
1 2 3 | |
โ ๏ธ Not POSIX โ avoid in portable scripts.
๐งช Array-Like Behavior
Bash supports arrays, but POSIX shells don't. Simulate with positional parameters:
1 2 3 4 5 6 7 8 9 | |
Or use delimited strings:
1 2 3 4 | |
๐งพ Portability Notes
| Feature | POSIX | Bash | Zsh |
|---|---|---|---|
${var:-default} |
โ | โ | โ |
${var:=default} |
โ | โ | โ |
${var:?error} |
โ | โ | โ |
${var^^} (uppercase) |
โ | โ | โ |
${var,,} (lowercase) |
โ | โ | โ |
${!var} (indirect) |
โ | โ | โ |
Arrays (${arr[@]}) |
โ | โ | โ |
๐งพ Summary
- Use
${var:-default}for optional configuration. - Use
${var:?error}for mandatory values. - Pattern substitutions (
##,%%,//) are powerful and portable. - Indirect references and case conversion are convenient but not portable.
- Simulate arrays in POSIX shells with
$@or delimited strings.
๐ Continue to: Conditionals and Tests