patternbashTip
Parameter expansion: substring, default, replacement, and case modification
Viewed 0 times
parameter expansionstring manipulationsubstringdefault valueprefix stripsuffix stripreplaceuppercaselowercase
Problem
Developers reach for external tools (sed, awk, python) for simple string operations that bash can do natively via parameter expansion, adding unnecessary subshell overhead.
Solution
Bash parameter expansion covers most common string operations:
${var:-default} # use default if var is unset or empty
${var:=default} # assign and use default if unset or empty
${var:?error msg} # exit with message if unset or empty
${#var} # length of string
${var:2:5} # substring: offset 2, length 5
${var#prefix} # remove shortest prefix match
${var##prefix} # remove longest prefix match
${var%suffix} # remove shortest suffix match
${var%%suffix} # remove longest suffix match
${var/old/new} # replace first occurrence
${var//old/new} # replace all occurrences
${var^} # uppercase first char (bash 4+)
${var^^} # uppercase all (bash 4+)
${var,} # lowercase first char (bash 4+)
${var,,} # lowercase all (bash 4+)
${var:-default} # use default if var is unset or empty
${var:=default} # assign and use default if unset or empty
${var:?error msg} # exit with message if unset or empty
${#var} # length of string
${var:2:5} # substring: offset 2, length 5
${var#prefix} # remove shortest prefix match
${var##prefix} # remove longest prefix match
${var%suffix} # remove shortest suffix match
${var%%suffix} # remove longest suffix match
${var/old/new} # replace first occurrence
${var//old/new} # replace all occurrences
${var^} # uppercase first char (bash 4+)
${var^^} # uppercase all (bash 4+)
${var,} # lowercase first char (bash 4+)
${var,,} # lowercase all (bash 4+)
Why
Parameter expansion runs in the current shell with no fork overhead. External tools like sed require a subshell (fork+exec), which is measurably slower in tight loops.
Gotchas
- ${var#pattern} and ${var%pattern} use glob patterns, not regex
- Case modification operators (^, ^^, ,, ,,) are bash 4+ only — not in zsh or older bash
- ${var:-} (with empty default) is a common idiom to safely expand possibly-unset vars with set -u
- Nested expansions: ${${var}:-default} does NOT work — use intermediate variable
Code Snippets
Parameter expansion cheat sheet
path="/usr/local/bin/myscript.sh"
# Get filename (remove path prefix)
echo "${path##*/}" # myscript.sh
# Get directory
echo "${path%/*}" # /usr/local/bin
# Remove extension
name="${path##*/}"
echo "${name%.*}" # myscript
# Default value
echo "${EDITOR:-vim}"
# Replace in string
echo "${path/bin/sbin}" # /usr/local/sbin/myscript.sh
# Uppercase
word="hello"
echo "${word^^}" # HELLO (bash 4+)Context
String manipulation without forking external processes in bash scripts
Revisions (0)
No revisions yet.