Shell Scripting / Bash Tricks
Quit checking if variables are empty with messy if statements
π§© The Challenge
You are writing a script and find yourself typing if [[ -z β$varβ ]] constantly just to provide a fallback value. It makes your code look like a wall of boilerplate text for no good reason.
π‘ The Fix
Bash has built-in parameter expansion operators that let you set defaults on the fly without breaking your flow. This keeps your scripts clean and readable, especially when dealing with environment variables.
echo "Result: ${MY_VAR:-default_value}"
${USER_DIR:=/tmp/backup}
βοΈ Why It Works
The colon tells bash to check if the variable is unset or null, and the dash immediately assigns a fallback right there in the expansion. It saves you three lines of code every single time you need to handle an empty config setting.
π Pro-Tip: Use the colon with the equals sign if you actually want to overwrite the variable with the default for the rest of the session.
Linux Tips & Tricks | Β© ngelinux.com | 11/27/2026
