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

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

if [ -z "${varname-}" ]; then
  ...
  varname=$(...)
fi

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.