Advanced Parameter Expansion
Demonstrates advanced Bash parameter expansion patterns including defaults, alternatives, substring, case modification, and variable indirection.
Code
#!/usr/bin/env bash
set -euo pipefail
# Default values
unset UNSET_VAR
echo "Default: ${UNSET_VAR:-default_value}"
echo "Default (set): ${UNSET_VAR:=now_set}"
echo "After set: $UNSET_VAR"
# Error if unset
: "${REQUIRED:?This variable is required}"
# Alternative value (if set)
existing="value"
echo "Alternative: ${existing:+was_set}"
echo "Alternative (unset): ${UNSET_VAR:+was_set}"
# Substring extraction
str="HelloWorld"
echo "Substring: ${str:5}"
echo "Substring len: ${str:0:5}"
echo "From end: ${str: -5}"
# Pattern removal
path="/usr/local/bin/program.sh"
echo "Basename: ${path##*/}"
echo "Dirname: ${path%/*}"
echo "No suffix: ${path%.*}"
echo "Suffix: ${path##*.}"
# Pattern substitution
text="The quick brown fox"
echo "Replace first: ${text/quick/slow}"
echo "Replace all: ${text//o/0}"
echo "Replace start: ${text/#The/A}"
echo "Replace end: ${text/%fox/cat}"
# Case modification (Bash 4+)
mixed="HelloWorld"
echo "Upper: ${mixed^^}"
echo "Lower: ${mixed,,}"
# Variable indirection
var_name="text"
echo "Indirect: ${!var_name}"
# Array parameter expansion
arr=("a" "b" "c" "d")
echo "All: ${arr[@]}"
echo "Count: ${#arr[@]}"
echo "Slice: ${arr[@]:1:2}"Report a problem with this exampleOpens a pre-filled issue on GitHub.