When your shell script variable isn’t as empty as you think
Technical Briefing | 7/13/2026
We have all been there. You write a script to cleanup some temporary directories, you set a variable to the path you want to delete, and then you hit a typo. Suddenly, you are staring at a production directory that just got wiped clean. Most people blame the logic, but the real culprit is usually the uninitialized or unset variable. It is a classic trap that still catches veterans who should know better.
Stop the bleeding with set -u
The shell is notoriously permissive. If you try to use a variable that has not been defined, it assumes you meant an empty string. That is rarely what you want. By adding set -u to the top of your scripts, the shell will throw an error and exit immediately if you reference an unset variable. It is the single most effective way to prevent catastrophic typos from doing real damage.
#!/bin/bash
set -u
rm -rf "$CLEANUP_DIR/"*
- Use set -u to force the shell to treat unset variables as an error
- Always quote your variables to prevent word splitting disasters
- Combine it with set -e to make sure the script halts on the first failed command
Sometimes you actually want a default value when a variable is missing, but you do not want to rely on the shell defaulting to empty. Use parameter expansion instead. Writing ${VAR:-default} makes your intent explicit. It tells anyone reading the code exactly what happens if the environment is not set up correctly. It is a small change, but it makes your automation predictable enough to actually trust.
The next time you are tempted to rely on a variable existing, remember that the shell is waiting to catch you on a technicality. Keep it explicit, keep it safe, and stop letting the shell decide what empty means for you.
