Parameter Expansion and Default Values
Parameter Expansion and Default Values
Parameter expansion allows you to inspect, modify, and assign fallback values to variables without invoking external tools like sed or awk.
Default Values and Fallbacks
# Use default if unset or empty: ${VAR:-default}
user_input=""
username="${user_input:-guest}"
echo "$username" # guest
# Assign default if unset or empty: ${VAR:=default}
# (Note: Does not work on positional parameters like $1)
${DATABASE_HOST:="localhost"}
# Throw error and exit if unset or empty: ${VAR:?error_message}
: "${CONFIG_FILE:?Error: CONFIG_FILE environment variable must be set}"
# Use alternate value if set and non-empty: ${VAR:+alternate}
${DEBUG:+"--verbose"}String Slicing and Length
text="LinuxDistribution"
# String length: ${#VAR}
echo "${#text}" # 17
# Substring extraction: ${VAR:offset:length}
echo "${text:0:5}" # Linux
echo "${text:5}" # Distribution
echo "${text: -4}" # tion (note the space before negative offset)Pattern Stripping and Substitution
filepath="/var/log/nginx/access.log.tar.gz"
# Strip shortest match from front: ${VAR#pattern}
echo "${filepath#*/}" # var/log/nginx/access.log.tar.gz
# Strip longest match from front: ${VAR##pattern} (equivalent to basename)
echo "${filepath##*/}" # access.log.tar.gz
# Strip shortest match from back: ${VAR%pattern}
echo "${filepath%.*}" # /var/log/nginx/access.log.tar
# Strip longest match from back: ${VAR%%pattern}
echo "${filepath%%.*}" # /var/log/nginx/access
# Replace first match: ${VAR/pattern/replacement}
echo "${filepath/log/archive}"
# Replace all matches: ${VAR//pattern/replacement}
echo "${filepath//\//_}" # _var_log_nginx_access.log.tar.gz