Bash & Shell Scripting (50 Qs)•Part 3: Advanced Text Processing & Production Internals (Senior / Lead)
Parameter Expansion Tricks: String replacement, default fallbacks (`$:-`, `$:=`, `$:?`), substring slicing, and length.
senior LevelCode Examplebash-shellAdvanced Text Processing
In Simple Words:
Bash parameter expansion performs fast string manipulation directly inside the shell process without spawning slow subshells (sed or awk):
bash
VAR="production-api-server-01"
# 1. Default value fallback if unset
PORT="${APP_PORT:-8080}"
# 2. Assign default value to variable if unset
DB_HOST="${DB_HOST:=localhost}"
# 3. Terminate script with error if variable is unset
API_KEY="${API_KEY:?Error: API_KEY must be provided!}"
# 4. String Length: ${#VAR}
echo "${#VAR}" # 24
# 5. Substring Slicing: ${VAR:offset:length}
echo "${VAR:0:10}" # production
# 6. Pattern Replacement: ${VAR/search/replace} (// for global)
echo "${VAR//-/_}" # production_api_server_01
# 7. Strip Prefix (# short, ## long) & Suffix (% short, %% long)
FILE="archive.tar.gz"
echo "${FILE%%.*}" # archive
echo "${FILE#*.}" # tar.gz