How to find whether or not a variable is empty in Bash

后端 未结 10 1095
深忆病人
深忆病人 2020-12-02 04:17

How can I check if a variable is empty in Bash?

相关标签:
10条回答
  • 2020-12-02 05:08
    [ "$variable" ] || echo empty
    : ${variable="value_to_set_if_unset"}
    
    0 讨论(0)
  • 2020-12-02 05:14

    You may want to distinguish between unset variables and variables that are set and empty:

    is_empty() {
        local var_name="$1"
        local var_value="${!var_name}"
        if [[ -v "$var_name" ]]; then
           if [[ -n "$var_value" ]]; then
             echo "set and non-empty"
           else
             echo "set and empty"
           fi
        else
           echo "unset"
        fi
    }
    
    str="foo"
    empty=""
    is_empty str
    is_empty empty
    is_empty none
    

    Result:

    set and non-empty
    set and empty
    unset
    

    BTW, I recommend using set -u which will cause an error when reading unset variables, this can save you from disasters such as

    rm -rf $dir
    

    You can read about this and other best practices for a "strict mode" here.

    0 讨论(0)
  • 2020-12-02 05:17
    if [[ "$variable" == "" ]] ...
    
    0 讨论(0)
  • 2020-12-02 05:20

    To check if variable v is not set

    if [ "$v" == "" ]; then
       echo "v not set"
    fi
    
    0 讨论(0)
提交回复
热议问题