Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Bash, how do I test if a variable is defined in "-u" mode

Tags:

bash

I just discovered set -u in bash and it helped me find several previously unseen bugs. But I also have a scenario where I need to test if a variable is defined before computing some default value. The best I have come up with for this is:

if [ "${variable-undefined}" == undefined ]; then
    variable="$(...)"
fi

which works (as long as the variable doesn't have the string value undefined). I was wondering if there was a better way?

like image 718
Ramon Avatar asked Jul 06 '12 12:07

Ramon


People also ask

How do you check if a variable is defined in bash?

To find out if a bash variable is defined: Return true if a bash variable is unset or set to the empty string: if [ -z ${my_variable+x} ]; Also try: [ -z ${my_bash_var+y} ] && echo "\$my_bash_var not defined"


2 Answers

This is what I've found works best for me, taking inspiration from the other answers:

if [ -z "${varname-}" ]; then
  ...
  varname=$(...)
fi
like image 127
Ramon Avatar answered Oct 09 '22 02:10

Ramon


What Doesn't Work: Test for Zero-Length Strings

You can test for undefined strings in a few ways. Using the standard test conditional looks like this:

# Test for zero-length string.
[ -z "$variable" ] || variable='foo'

This will not work with set -u, however.

What Works: Conditional Assignment

Alternatively, you can use conditional assignment, which is a more Bash-like way to do this. For example:

# Assign value if variable is unset or null.
: "${variable:=foo}"

Because of the way Bash handles expansion of this expression, you can safely use this with set -u without getting a "bash: variable: unbound variable" error.

like image 34
Todd A. Jacobs Avatar answered Oct 09 '22 02:10

Todd A. Jacobs