I need to check a variable's existence in an if statement. Something to the effect of:

if [ -v $somevar ]
    echo "Variable somevar exists!"
    echo "Variable somevar does not exist!"

And the closest question to that was this, which doesn't actually answer my question.

12 Answers 12


In modern bash (version 4.2 and above):

[[ -v name_of_var ]]

From help test:

-v VAR, True if the shell variable VAR is set

  • 3
    Also works with single brackets: [ -v name_of_var ]. – meuh Jun 25 '15 at 16:45
  • 7
    beware that for hashes and arrays, it returns false unless the variable has an element of key/indice "0". For namerefs, it tests whether the target is defined. It doesn't work for special parameters like $1, $-, $#... – Stéphane Chazelas Dec 1 '15 at 17:33
  • 4
    This feature is only in the bash builtin test or [ ; It is not available in /usr/bin/test. Compare man test with help test. – Mark Lakata Aug 26 '16 at 17:46
  • @MarkLakata Right, because external commands cannot know the internal state of the shell. – Chris Down Sep 1 '16 at 15:29
  • umm shouldn't it always be [[ -v "$name_of_var" ]] ? – Alexander Mills Nov 25 '16 at 4:13

Depends what you mean by exists.

Does a variable that has been declared but not assigned exist?

Does an array (or hash) variable that has been assigned an empty list exist?

Does a nameref variable pointing to a variable that currently isn't assigned exist?

Do you consider $-, $#, $1 variables? (POSIX doesn't).

In Bourne-like shells, the canonical way is:

if [ -n "${var+set}" ]; then
  echo '$var was set'

That works for scalar variables and other parameters to tell if a variable has been assigned a value (empty or not, automatically, from the environment, assigments, read, for or other).

For shells that have a typeset or declare command, that would not report as set the variables that have been declared but not assigned except in zsh.

For shells that support arrays, except for yash and zsh that would not report as set array variables unless the element of indice 0 has been set.

For bash (but not ksh93 nor zsh), for variables of type associative array, that would not report them as set unless their element of key "0" has been set.

For ksh93 and bash, for variables of type nameref, that only returns true if the variable referenced by the nameref is itself considered set.

For ksh, zsh and bash, a potentially better approach could be:

if ((${#var[@]})); then
  echo '$var (or the variable it references for namerefs) or any of its elements for array/hashes has been set'

For ksh93, zsh and bash 4.4 or above, there's also:

if typeset -p var 2> /dev/null | grep -q '^'; then
  echo '$var exists'

Which will report variables that have been set or declared.

  • 1
    declare -p / typeset -p works in bash now too. – cas May 2 '16 at 20:12
  • 1
    @cas, no. Not for declared but not set variables. Try bash -c 'typeset -i a; typeset -p a' and compare with ksh93 or zsh. – Stéphane Chazelas May 2 '16 at 21:34
  • +1 Thanks for point me here. Also see my question unix.stackexchange.com/q/280893/674 – Tim May 3 '16 at 20:15
  • @cas, that changed with bash-4.4 (released in September 2016), I've edited that in. – Stéphane Chazelas Nov 2 '17 at 12:55

As mentioned in the answer on SO, here is a way to check:

if [ -z ${somevar+x} ]; then echo "somevar is unset"; else echo "somevar is set to '$somevar'"; fi

where ${somevar+x} is a parameter expansion which evaluates to the null if var is unset and substitutes the string "x" otherwise.

Using -n, as suggested by the other answer, will only check if the variable contains empty string. It will not check its existence.

  • 2
    You need to quote $somevar to handle IFS=x. Either that or quote x. – mikeserv Jun 26 '15 at 0:02
  • 1
    @mikeserv Thanks, I like learning about edge cases :) Do you mean if [ -z "${somevar+x}" ]? Would the quoting still be required inside [[ and ]]? – Tom Hale Sep 3 '18 at 14:19
  • @TomHale - yes, in rare cases. the [ test routines accept command line parameters, and so the usual expansions and interpretations as ordered in the usual way should be relied upon to render at invocation of the test applied that which you should cause to be read thereby by any program command line. test{!+"!"} – mikeserv Oct 10 '18 at 6:02
  • @mikeserv I guess your yes is to my 2nd question... Is the first a yes, too? – Tom Hale Oct 10 '18 at 14:14
  • 1
    +1; this appears to be the simplest way to do this when set -u is in effect and the Bash version is pre-4.2. – Kyle Strand Jan 8 at 22:56


! (: "${somevar?}") 2>/dev/null && echo somevar unset

or you can let your shell show the message for you:

(: "${somevar?}")
zsh: somevar: parameter not set
  • @mikeserv: Yeah, of course, there's many way to do it. Firstly, I think I will duplicated it with this. But in this question, the OP want to check only, he didn't claim that he want to exit or report if variable unset, so I came with a check in subshell. – cuonglm Jun 26 '15 at 1:46
  • 2
    Well, i know, but it's precisely because you have to do it in a subshell like that which indicates it might not be the best way to test here - that's a halt action on failure, it doesn't allow for any simple means to handle a failure. Portably even a trap can only work on EXIT. That's all I'm saying - it just doesn't apply as a pass/fail very well. And this isn't me talking either - i've done exactly this before and it took a little comment chat just like this to convince me. So, I just thought I'd pay it forward. – mikeserv Jun 26 '15 at 1:51
  • 1
    @mikeserv: Well, well, it's a good point. I only wonder, does adding that can make the OP confuse with the syntax :) – cuonglm Jun 26 '15 at 2:24
if set|grep '^somevar=' >/dev/null;then
    echo "somevar exists"
    echo "does not exist"
  • I would imagine this to be somewhat inefficient, but it is very simple and sh compatible, which is just what I need. – hoijui Aug 28 at 8:27
printf ${var+'$var exists!\n'}

...will print nothing at all when it doesn't. Or...

printf $"var does%${var+.}s exist%c\n" \ not !

...will tell you either way.

you can use the return value of a test to dynamically expand to the appropriate format string for your condition:

[ "${var+1}" ]
printf $"var does%.$?0s exist%c\n" \ not !

You can also make printf fail based on a substitution...

printf $"var does%${var+.}s exist%c\n%.${var+b}d" \
        \ not ! \\c >&"$((2${var+-1}))" 2>/dev/null

...which prints $var does not exist! to stderr and returns other than 0 when $var is unset, but prints $var does exist! to stdout and returns 0 when $var is set.


This simple line works (and works on most POSIX shells):

${var+"false"} && echo "var is unset"

Or, written in a longer form:

unset var

if ${var+"false"}
   echo "var is unset"

The expansion is:

  • If the var has a value (even null), false is replaced
  • If the var has "no value", then "no value" (null) is replaced.

The ${var+"false"} expansion expands to either "null" of "false".
Then, "nothing" or the "false" is executed, and the exit code set.

There is no need to call the command test ([ or [[) as the exit value is set by the (execution of) the expansion itself.

  • Yes, except in some old versions of zsh in sh emulation when $IFS contains f, a, l, s or e. Like for other answers, there's the case of arrays, hashes, or other types of variables which one may want to mention. – Stéphane Chazelas Dec 1 '15 at 21:00
  • @StéphaneChazelas I wrote most POSIX shells. most means In the greatest number of instances, not all. ... ... So, yes, in an obscure condition when $IFS contains f, a, l, s or e and for some obscure shell some old versions of zsh this fails: What a shock!. I should assume that such bug has been solved long ago. ... ... Are you proposing that we must write code for long ago broken shells?. – user79743 May 30 '16 at 1:43
  • @StéphaneChazelas Also: The question title is very specific: Bash. – user79743 May 30 '16 at 1:46
  • binary zebra??? – mikeserv Oct 16 '18 at 19:12

The pure shell way:

[ "${var+1}" ] || echo "The variable has not been set"

Test script:

echo "Test 1, var has not yet been created"
[ "${var+1}" ] || echo "The variable has not been set"

echo "Test 2, var=1"
[ "${var+1}" ] || echo "The variable has not been set"

echo "Test 3, var="
[ "${var+1}" ] || echo "The variable has not been set"

echo "Test 4, unset var"
unset var
[ "${var+1}" ] || echo "The variable has not been set"
echo "Done"


Test 1, var has not yet been created
The variable has not been set
Test 2, var=1
Test 3, var=
Test 4, unset var
The variable has not been set
  • 1
    Fails when variable set to null string. – Tom Hale Sep 3 '18 at 14:22

With bash 4.4.19 the following worked for me. Here is a complete example

$export MAGENTO_DB_HOST="anyvalue"


if [ -z "$MAGENTO_DB_HOST" ]; then
    echo "Magento variable not set"

You can't use if command to check the existence of declared variables in bash however -v option exists in newer bash, but it's not portable and you can't use it in older bash versions. Because when you are using a variable if it doesn't exists it will born at the same time.

E.g. Imagine that I didn't use or assign a value to the MYTEST variable, but when you are using echo command it shows you nothing! Or if you are using if [ -z $MYTEST ] it returned zero value! It didn't return another exit status, which tells you that this variable doesn't exist!

Now you have two solutions (Without -v option):

  1. Using declare command.
  2. Using set command.

For example:

set | grep MYTEST
declare | grep MYTEST

But unfortunately these commands shows you loaded functions in memory too! You can use declare -p | grep -q MYTEST ; echo $? command for cleaner result.


Function to check if variable is declared/unset

including empty $array=()

In addition to @Gilles's answer

case " ${!foobar*} " in
  *" foobar "*) echo "foobar is declared";;
  *) echo "foobar is not declared";;

-- 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

bash function that works for both scalar and array types:


has_declare() { # check if variable is set at all
    local "$@" # inject 'name' argument in local scope
    &>/dev/null declare -p "$name" # return 0 when var is present


if has_declare name="vars_name" ; then
   echo "variable present: vars_name=$vars_name"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.