Skip to main content
4 of 4
replaced http://unix.stackexchange.com/ with https://unix.stackexchange.com/

Function to check if variable is declared/unset

including empty $array=()


In addition to @Gilles's [answer](https://unix.stackexchange.com/a/56846/158123)
case " ${!foobar*} " in *" foobar "*) echo "foobar is declared";; *) echo "foobar is not declared";; esac 

-- which I did not find a way for to encapsulate it within a function -- I'd like to add a simple version, which is partly based on Richard Hansen's answer, but does address also the pitfall that occurs with an empty array=():

# The first parameter needs to be the name of the variable to be checked. # (See example below) var_is_declared() { { [[ -n ${!1+anything} ]] || declare -p $1 &>/dev/null;} } var_is_unset() { { [[ -z ${!1+anything} ]] && ! declare -p $1 &>/dev/null;} } 
  • By first testing if the variable is (un)set, the call to declare can be avoided, if not necessary.
  • If however $1 contains the name of an empty $array=(), the call to declare would make sure we get the right result
  • There's never much data passed to /dev/null as declare is only called if either the variable is unset or an empty array.

With the following code the functions can be tested:
( # start a subshell to encapsulate functions/vars for easy copy-paste into the terminal # do not use this extra parenthesis () in a script! var_is_declared() { { [[ -n ${!1+anything} ]] || declare -p $1 &>/dev/null;} } var_is_unset() { { [[ -z ${!1+anything} ]] && ! declare -p $1 &>/dev/null;} } :; echo -n 'a; '; var_is_declared a && echo "# is declared" || echo "# is not declared" a=; echo -n 'a=; '; var_is_declared a && echo "# is declared" || echo "# is not declared" a="sd"; echo -n 'a="sd"; '; var_is_declared a && echo "# is declared" || echo "# is not declared" a=(); echo -n 'a=(); '; var_is_declared a && echo "# is declared" || echo "# is not declared" a=(""); echo -n 'a=(""); '; var_is_declared a && echo "# is declared" || echo "# is not declared" unset a; echo -n 'unset a; '; var_is_declared a && echo "# is declared" || echo "# is not declared" echo ; :; echo -n 'a; '; var_is_unset a && echo "# is unset" || echo "# is not unset" a=; echo -n 'a=; '; var_is_unset a && echo "# is unset" || echo "# is not unset" a="foo"; echo -n 'a="foo"; '; var_is_unset a && echo "# is unset" || echo "# is not unset" a=(); echo -n 'a=(); '; var_is_unset a && echo "# is unset" || echo "# is not unset" a=(""); echo -n 'a=(""); '; var_is_unset a && echo "# is unset" || echo "# is not unset" unset a; echo -n 'unset a; '; var_is_unset a && echo "# is unset" || echo "# is not unset" ) 

The script should return

a; # is not declared a=; # is declared a="foo"; # is declared a=(); # is declared a=(""); # is declared unset a; # is not declared a; # is unset a=; # is not unset a="foo"; # is not unset a=(); # is not unset a=(""); # is not unset unset a; # is unset