SnapOverflow

SnapOverflow Logo SnapOverflow Logo

SnapOverflow Navigation

  • Home
  • Server
  • Ubuntu

Mobile menu

Close
  • Home
  • System Administrators
    • Hot Questions
    • New Questions
    • Tags
  • Ubuntu
    • Hot Questions
    • New Questions
    • Tags
  • Help
Home / server / Questions / 7503
Accepted
Brent
Brent
Asked: 2009-05-13 09:54:48 +0800 CST2009-05-13 09:54:48 +0800 CST 2009-05-13 09:54:48 +0800 CST

How to determine if a bash variable is empty?

  • 772

What is the best way to determine if a variable in bash is empty ("")?

I have heard that it is recommended that I do if [ "x$variable" = "x" ]

Is that the correct way? (there must be something more straightforward)

scripting bash variables
  • 15 15 Answers
  • 1279404 Views

15 Answers

  • Voted
  1. Best Answer
    duffbeer703
    2009-05-13T10:06:44+08:002009-05-13T10:06:44+08:00

    This will return true if a variable is unset or set to the empty string ("").

    if [ -z "${VAR}" ];
    
    • 1227
  2. Dennis Williamson
    2012-02-25T19:37:43+08:002012-02-25T19:37:43+08:00

    In Bash, when you're not concerned with portability to shells that don't support it, you should always use the double-bracket syntax:

    Any of the following:

    if [[ -z $variable ]]
    if [[ -z "$variable" ]]
    if [[ ! $variable ]]
    if [[ ! "$variable" ]]
    

    In Bash, using double square brackets, the quotes aren't necessary. You can simplify the test for a variable that does contain a value to:

    if [[ $variable ]]
    

    This syntax is compatible with ksh (at least ksh93, anyway). It does not work in pure POSIX or older Bourne shells such as sh or dash.

    See my answer here and BashFAQ/031 for more information about the differences between double and single square brackets.

    You can test to see if a variable is specifically unset (as distinct from an empty string):

    if [[ -z ${variable+x} ]]
    

    where the "x" is arbitrary.

    If you want to know whether a variable is null but not unset:

    if [[ -z $variable && ${variable+x} ]]
    
    • 299
  3. Richard Hansen
    2012-04-25T12:39:38+08:002012-04-25T12:39:38+08:00

    A variable in bash (and any POSIX-compatible shell) can be in one of three states:

    • unset
    • set to the empty string
    • set to a non-empty string

    Most of the time you only need to know if a variable is set to a non-empty string, but occasionally it's important to distinguish between unset and set to the empty string.

    The following are examples of how you can test the various possibilities, and it works in bash or any POSIX-compatible shell:

    if [ -z "${VAR}" ]; then
        echo "VAR is unset or set to the empty string"
    fi
    if [ -z "${VAR+set}" ]; then
        echo "VAR is unset"
    fi
    if [ -z "${VAR-unset}" ]; then
        echo "VAR is set to the empty string"
    fi
    if [ -n "${VAR}" ]; then
        echo "VAR is set to a non-empty string"
    fi
    if [ -n "${VAR+set}" ]; then
        echo "VAR is set, possibly to the empty string"
    fi
    if [ -n "${VAR-unset}" ]; then
        echo "VAR is either unset or set to a non-empty string"
    fi
    

    Here is the same thing but in handy table form:

                            +-------+-------+-----------+
                    VAR is: | unset | empty | non-empty |
    +-----------------------+-------+-------+-----------+
    | [ -z "${VAR}" ]       | true  | true  | false     |
    | [ -z "${VAR+set}" ]   | true  | false | false     |
    | [ -z "${VAR-unset}" ] | false | true  | false     |
    | [ -n "${VAR}" ]       | false | false | true      |
    | [ -n "${VAR+set}" ]   | false | true  | true      |
    | [ -n "${VAR-unset}" ] | true  | false | true      |
    +-----------------------+-------+-------+-----------+
    

    The ${VAR+foo} construct expands to the empty string if VAR is unset or to foo if VAR is set to anything (including the empty string).

    The ${VAR-foo} construct expands to the value of VAR if set (including set to the empty string) and foo if unset. This is useful for providing user-overridable defaults (e.g., ${COLOR-red} says to use red unless the variable COLOR has been set to something).

    The reason why [ x"${VAR}" = x ] is often recommended for testing whether a variable is either unset or set to the empty string is because some implementations of the [ command (also known as test) are buggy. If VAR is set to something like -n, then some implementations will do the wrong thing when given [ "${VAR}" = "" ] because the first argument to [ is erroneously interpreted as the -n operator, not a string.

    • 294
  4. Amandasaurus
    2009-06-12T05:19:09+08:002009-06-12T05:19:09+08:00

    -z is a the best way.

    Another options I've used is to set a variable, but it can be overridden by another variable eg

    export PORT=${MY_PORT:-5432}
    

    If the $MY_PORT variable is empty, then PORT gets set to 5432, otherwise PORT is set to the value of MY_PORT. Note the syntax include the colon and dash.

    • 44
  5. MikeyB
    2009-05-13T10:21:43+08:002009-05-13T10:21:43+08:00

    If you're interested in distinguishing the cases of set-empty versus unset status, look at the -u option for bash:

    $ set -u
    $ echo $BAR
    bash: BAR: unbound variable
    $ [ -z "$BAR" ] && echo true
    bash: BAR: unbound variable
    $ BAR=""
    $ echo $BAR
    
    $ [ -z "$BAR" ] && echo true
    true
    
    • 25
  6. errant.info
    2011-10-20T19:58:35+08:002011-10-20T19:58:35+08:00

    An alternate I've seen to [ -z "$foo" ] is the following, however I'm not sure why people use this method, anyone know?

    [ "x${foo}" = "x" ]
    

    Anyway if you're disallowing unset variables (either by set -u or set -o nounset), then you'll run into trouble with both of those methods. There's a simple fix to this:

    [ -z "${foo:-}" ]
    

    Note: this will leave your variable undef.

    • 8
  7. Luca Borrione
    2012-09-01T12:11:38+08:002012-09-01T12:11:38+08:00

    The question asks how to check if a variable is an empty string and the best answers are already given for that.
    But I landed here after a period passed programming in php and what I was actually searching was a check like the empty function in php working in a bash shell.
    After reading the answers I realized I was not thinking properly in bash, but anyhow in that moment a function like empty in php would have been soooo handy in my bash code.
    As I think this can happen to others, I decided to convert the php empty function in bash

    According to the php manual:
    a variable is considered empty if it doesn't exist or if its value is one of the following:

    • "" (an empty string)
    • 0 (0 as an integer)
    • 0.0 (0 as a float)
    • "0" (0 as a string)
    • an empty array
    • a variable declared, but without a value

    Of course the null and false cases cannot be converted in bash, so they are omitted.

    function empty
    {
        local var="$1"
    
        # Return true if:
        # 1.    var is a null string ("" as empty string)
        # 2.    a non set variable is passed
        # 3.    a declared variable or array but without a value is passed
        # 4.    an empty array is passed
        if test -z "$var"
        then
            [[ $( echo "1" ) ]]
            return
    
        # Return true if var is zero (0 as an integer or "0" as a string)
        elif [ "$var" == 0 2> /dev/null ]
        then
            [[ $( echo "1" ) ]]
            return
    
        # Return true if var is 0.0 (0 as a float)
        elif [ "$var" == 0.0 2> /dev/null ]
        then
            [[ $( echo "1" ) ]]
            return
        fi
    
        [[ $( echo "" ) ]]
    }
    



    Example of usage:

    if empty "${var}"
        then
            echo "empty"
        else
            echo "not empty"
    fi
    



    Demo:
    the following snippet:

    #!/bin/bash
    
    vars=(
        ""
        0
        0.0
        "0"
        1
        "string"
        " "
    )
    
    for (( i=0; i<${#vars[@]}; i++ ))
    do
        var="${vars[$i]}"
    
        if empty "${var}"
            then
                what="empty"
            else
                what="not empty"
        fi
        echo "VAR \"$var\" is $what"
    done
    
    exit
    

    outputs:

    VAR "" is empty
    VAR "0" is empty
    VAR "0.0" is empty
    VAR "0" is empty
    VAR "1" is not empty
    VAR "string" is not empty
    VAR " " is not empty
    

    Having said that in a bash logic the checks on zero in this function can cause side problems imho, anyone using this function should evaluate this risk and maybe decide to cut those checks off leaving only the first one.

    • 6
  8. namewithoutwords
    2010-01-27T06:02:09+08:002010-01-27T06:02:09+08:00

    the entire if-then and -z are unnecessary.

    [ "$foo" ] && echo "foo is not empty"
    [ "$foo" ] || echo "foo is indeed empty"
    
    • 5
  9. Fedir RYKHTIK
    2011-12-10T07:15:29+08:002011-12-10T07:15:29+08:00

    Personally prefer more clear way to check :

    if [ "${VARIABLE}" == "" ]; then
      echo VARIABLE is empty
    else
      echo VARIABLE is not empty
    fi
    
    • 5
  10. gluk47
    2015-11-10T08:46:15+08:002015-11-10T08:46:15+08:00

    My 5 cents: there is also a shorter syntax than if ..., this one:

    VALUE="${1?"Usage: $0 value"}"
    

    This line will set VALUE if an argument has been supplied and will print an error message prepended with the script line number in case of an error (and will terminate the script execution).

    Another example can be found in the abs-guide (search for «Example 10-7»).

    • 5

Sidebar

Stats

  • Questions 681965
  • Answers 980273
  • Best Answers 280204
  • Users 287326
  • Popular
  • Answers
  • Marko Smith

    Ping a Specific Port

    • 18 Answers
  • Marko Smith

    What port does SFTP use?

    • 6 Answers
  • Marko Smith

    Resolve host name from IP address

    • 8 Answers
  • Marko Smith

    How can I sort du -h output by size

    • 30 Answers
  • Marko Smith

    Command line to list users in a Windows Active Directory group?

    • 9 Answers
  • Marko Smith

    What's the command-line utility in Windows to do a reverse DNS look-up?

    • 14 Answers
  • Marko Smith

    How to check if a port is blocked on a Windows machine?

    • 4 Answers
  • Marko Smith

    What port should I open to allow remote desktop?

    • 9 Answers
  • Marko Smith

    What is a Pem file and how does it differ from other OpenSSL Generated Key File Formats?

    • 3 Answers
  • Marko Smith

    How to determine if a bash variable is empty?

    • 15 Answers
  • Martin Hope
    Davie Ping a Specific Port 2009-10-09 01:57:50 +0800 CST
  • Martin Hope
    Deepak Mittal How to run a server on port 80 as a normal user on Linux? 2008-11-11 06:31:11 +0800 CST
  • Martin Hope
    MikeN In Nginx, how can I rewrite all http requests to https while maintaining sub-domain? 2009-09-22 06:04:43 +0800 CST
  • Martin Hope
    Tom Feiner How can I sort du -h output by size 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    0x89 What is the difference between double and single square brackets in bash? 2009-08-10 13:11:51 +0800 CST
  • Martin Hope
    kch How do I change my private key passphrase? 2009-08-06 21:37:57 +0800 CST
  • Martin Hope
    Kyle Brandt How does IPv4 Subnetting Work? 2009-08-05 06:05:31 +0800 CST
  • Martin Hope
    Noah Goodrich What is a Pem file and how does it differ from other OpenSSL Generated Key File Formats? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent How to determine if a bash variable is empty? 2009-05-13 09:54:48 +0800 CST
  • Martin Hope
    cletus How do you find what process is holding a file open in Windows? 2009-05-01 16:47:16 +0800 CST

Related Questions

Trending Tags

linux nginx windows networking ubuntu domain-name-system amazon-web-services active-directory apache-2.4 ssh

Explore

  • Home
  • Questions
    • Hot Questions
    • New Questions
  • Tags
  • Help

Footer

SnapOverflow

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Help

© 2022 SOF-TR. All Rights Reserve