Site icon New Generation Enterprise Linux

Quit checking if variables are empty with messy if statements

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

0 0 votes
Article Rating
Exit mobile version