I once inherited a deployment script from a former colleague that would silently fail — or worse, do something destructive — whenever an environment variable wasn’t set. There was no fallback, no default, just a blind assumption that every variable would always be populated correctly. Fixing that script taught me just how much Bash’s parameter expansion syntax can do for default values, and it’s a habit I now build into almost every script I write. In this article I’ll walk you through every practical way to set default values in Bash, from the simplest case to more advanced patterns.
Why Default Values Matter
Scripts rarely run in a perfectly controlled environment. Arguments get forgotten, environment variables get unset, and configuration files sometimes don’t exist yet. A script that assumes everything will always be provided correctly is a script that will eventually fail in a confusing way, often at the worst possible time — like during an automated deployment at 2 AM. Default values let your script degrade gracefully instead of crashing or behaving unpredictably.
#!/bin/bash
# If MY_VAR is unset or null, set it to "default_value"
MY_VAR="${MY_VAR:-default_value}"
echo "MY_VAR is set to: $MY_VAR"
In this example, if the variable MY_VAR is unset or null, it will be set to “default_value”.
If you want to set a default value for a command-line argument, you can use the $1 variable which represents the first argument passed to the script. Here’s an example:
#!/bin/bash
# If the first argument is unset or null, set it to "default_arg"
arg1="${1:-default_arg}"
echo "First argument is set to: $arg1"
If you run this script without any arguments (./script.sh), it will use “default_arg” as the value of $arg1. If you run it with an argument (./script.sh custom_arg), it will use the provided argument instead.
Keep in mind that these techniques allow you to set default values for variables in a Bash script. They won’t directly modify the environment variables of your shell session. If you want to set default values for environment variables in your current shell session, you can simply assign them a value if they are unset:
MY_VAR=${MY_VAR:-default_value}
This will set MY_VAR to “default_value” if it is unset or null in your current shell session.
