Bash Shell: Find Out If a Variable Is Set or Not

How do I check if a bash shell variable called $input is defined or not under BSD / Apple OS X / Unix / Linux like operating systems?

Method #1: Bash Variable Existence Check

The syntax is as follows to determine if $input is defined or not:

${Variable?Error \$Variable is not defined}

OR

${Variable:?Error \$Variable is not defined}

In this example your script will stop executing if the variable $input is not defined:

input="Foo bar"
echo ${input?Error \$input is not defined.}
unset input
echo ${input?Error \$input is not defined.}

Sample outputs:

Foo bar
bash: input: Error $input is not defined.

In this example, make sure $input is defined and is not empty, enter:

[[  $input && ${input-x} ]] 
input="Foo" 
[[  $input && ${input-x} ]] && echo "Found" || echo "Not found"
unset input
[[  $input && ${input-x} ]] && echo "Found" || echo "Not found"

Here is an example that make sure $_php_map_extension is defined:

        # read config data
        loadConfigData "${_t_domain_php_conf}" $LINENO "${FUNCNAME[0]}"
 
	# make sure it is defined and not empty 
	if [[ $_php_map_extension && ${_php_map_extension-_} ]]
        then
                at=${#_php_map_extension[*]}                                            # get total elements in an array
                s=""
                echo '## Map extension to .php? ##' 
                echo 'fastcgi.map-extensions = ('  
                for (( i=0; i<${at}; i++ ));
                do
                        [ $i -lt $(( $at - 1 )) ] && s="," || s=""                      # remove , for last item in an array                    
                        echo "      \".${_php_map_extension[i]}\" => \".php\"${s}" 
                done
                echo ')'
	else 
		echo "Skiping php map extension as \$_php_map_extension is not defined in /usr/local/etc/nixcraft/conf/php.conf."
        fi

Sample outputs:

Skiping php map extension as $_php_map_extension is not defined in /usr/local/etc/nixcraft/conf/php.conf

OR

## Map extension to .php? ##
fastcgi.map-extensions = (
      ".html" => ".php",
      ".htm" => ".php",
      ".phtml" => ".php",
      ".php3" => ".php",
      ".php4" => ".php"
)

Method #2: isvarset() function

The above examples are useful for a sanity checking. Finally, you can use the following code:

isvarset(){
 local v="$1"
 [[ ! ${!v} && ${!v-unset} ]] && echo "Variable not found." || echo "Variable found."
}
 
# find out if $vech defined or not
vech="Bus" && isvarset vech
vech="" && isvarset vech
unset vech && isvarset vech

Method 3: Using the Length of STRING

The -z option to test command returns TRUE of the Length of STRING is zero. You can use the following syntax:

### set or not???
input="Foo"
[ -z "${input+x}" ] && echo "\$input is not set" || echo "\$input found and is set to \"$input\"."
 
### Not set at ALL
unset input
[ -z "${input+x}" ] && echo "\$input is not set" || echo "\$input found and is set to \"$input\"."
 
### 'set but empty' or not?
input=""
[ -z "$input" -a "${input+x}" = "x" ] && echo "\$input variable is set with empty value." || echo "\$input found and is set to "\$input\""

The above syntax will tell if a variable is defined or not defined or defined with a empty value in a bash shell script.


🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 4 comments so far... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
4 comments… add one
  • Chris F.A. Johnson Oct 6, 2011 @ 2:19
    varstatus()
    {
      if [ -n "$1" ]
      then
        echo Set and not empty
      elif [ -n "${1+x}" ]
      then
        echo Set but empty
      else
        echo Not set
      fi
    }
    
    varstatus ''
    varstatus
    varstatus qwerty
    
  • lazarus Sep 23, 2012 @ 21:27

    Hi vitek,
    in method 3, last line there’s a typo:
    \”$input\” instead of “\$input\”
    Kind regards
    lazarus

  • Guillermo Dec 19, 2012 @ 16:29

    You have an easier way to check if a variable is set or not even if you enable -u (set -u = Treat unset variables as an error when substituting.)

    [ “${var:-NOTDEF}” != “NOTDEF” ] && echo var is defined || echo var is not defined.

    From man bash

    ${parameter:-word}
    Use Default Values. If parameter is unset or null, the expansion of word is
    substituted. Otherwise, the value of parameter is substituted.

  • dj Feb 14, 2013 @ 4:12

    The bash parameter expansions (:-, :=, :?, :+) are very helpful.
    See Parameter Expansion in the bash man page or read here:
    http://tiswww.case.edu/php/chet/bash/bash.html#lbBB

    But there is an additional option with Bash 4.2. The -v operator:

    snippet:
    test/[/[[ have a new -v variable unary operator, which returns success if `variable’ has been set.

    link (search for -v):
    http://tiswww.case.edu/php/chet/bash/CHANGES
    or read
    http://tiswww.case.edu/php/chet/bash/bash.html#lbBW

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum