Skip to main content

Assigning default values to variables in Bash

You can use this syntax to set default values for environment variables while allowing them to be overridden when the script is called:

# Default env var values which can be overridden by the user
# See: https://emmer.dev/blog/bash-environment-variable-defaults/
: "${CONFIGOME_ENV:=default}"
 
export CONFIGOME_ENV="${CONFIGOME_ENV}"
# ...

The : part expands arguments but otherwise does nothing.

The ${variable:=value} part assigns value to variable only if variable is unset or null, which is exactly what we want (i.e. don’t override them if the user set them, but give them a default value if currently empty).

Use case, a script which can optionally receive options as environment variables (which can be an easier way to pass config options in some environments, e.g. docker).

Credit for all of this: Bash Environment Variable Defaults | Christian Emmer

Confirmation of using bash parameter expansion for this: Assigning default values to shell variables with a single command in bash - Stack Overflow

Bash docs for shell parameter expansion feature: Shell Parameter Expansion (Bash Reference Manual)

Bash docs for what “shell parameter” means: Shell Parameters (Bash Reference Manual)