Specifying default values

If a variable may not have a value in a script, you can specify a default or "fallback" value for it with the form "${myvar:-default}", where default is the string you want to use instead of the variable's value if it's unset or blank. This can be useful for default directories that can be overridden by environment variables, if present:

cd -- "${MYSCRIPT_DIR:-/usr/local/myscript}"
...

This script will change into the directory named in the MYSCRIPT_DIR environment variable if set, or the /usr/local/myscript directory it it is not set, or if it is blank.

If you use the  := characters instead of :-, you can additionally assign the default value to the environment variable for the rest of the script:

cd -- "${MYSCRIPT_DIR:=/usr/local/myscript}" ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.