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}"Advanced parameter expansion: :- provides defaults, := sets defaults, :+ provides alternatives, :? errors if unset. ##/% remove longest/shortest patterns from start/end. // replaces all matches. ^^/,, convert case. !var does indirect expansion. These patterns replace many external commands, improving performance and portability.
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
Report a problem with this exampleOpens a pre-filled issue on GitHub.