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
set -u
This is what I've found works best for me, taking inspiration from the other answers:
if [ -z "${varname-}" ]; then ... varname=$(...) fi