Bash: Error `Unbound variable' when testing unset variable
From FVue
Problem
I have defined strict bash settings:
set -o errexit # Exit on error set -o nounset # Trigger error when expanding unset variables
But now I get the error $1: Unbound variable when I execute this line:
[ $# -eq 0 -o "$1" = --help ] && showUsage()
Solutions
`[[' compound command
Use the `[[' compound command for more intelligent parsing, without any `unbound' error:
[[ $# == 0 || $1 == --help ]] && showUsage()
This works because $1 == --help
is only evaluated if the first expression $# == 0
equals false.
Parameter expansion
Use parameter expansion for positional parameter $1:
[ $# -eq 0 -o "${1:-unset}" = --help ] && showUsage()
From info bash
:
`${PARAMETER:-WORD}'
- If PARAMETER is unset or null, the expansion of WORD is substituted. Otherwise, the value of PARAMETER is substituted.
Advertisement