Skip to content

Instantly share code, notes, and snippets.

@knbknb
Last active July 27, 2022 09:09
Show Gist options
  • Save knbknb/2f5dd05a952067be542012cc36211b60 to your computer and use it in GitHub Desktop.
Save knbknb/2f5dd05a952067be542012cc36211b60 to your computer and use it in GitHub Desktop.
bash-variables set, unset, empty, +/-defaults (Stackoverflow answer)

SO Answer

How to check if a variable is set in Bash?
Q: from 2011 A: from 2021

https://stackoverflow.com/a/65482850/202553

if test "${name+x}"; then
    echo 'name is set'
else
    echo 'name is not set'
fi

This question already has a lot of answers, but none of them offered bona fide Boolean expressions to clearly differentiate between variables values.

Here are some unambiguous expressions that I worked out:

Expression in script name='fish' name='' unset name
test "$name" TRUE f f
test -n "$name" TRUE f f
test ! -z "$name" TRUE f f
test ! "${name-x}" f TRUE f
test ! "${name+x}" f f TRUE

By the way, these expressions are equivalent: test <=> [ ]

Other ambiguous expressions to be used with caution:

Expression in script name='fish' name='' unset name
test "${name+x}" TRUE TRUE f
test "${name-x}" TRUE f TRUE
test -z "$name" f TRUE TRUE
test ! "$name" f TRUE TRUE
test ! -n "$name" f TRUE TRUE
test "$name" = '' f TRUE TRUE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment