zoukankan      html  css  js  c++  java
  • How to find variable is empty in shell script

    (1).

    var=""
    if [ -n "$var" ]; then
        echo "not empty"
    else
        echo "empty"
    fi

    (2).

    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 "" ) ]]
    }
    usage:
    if empty "${var}"
        then
            echo "empty"
        else
            echo "not empty"
    fi

    (3).

    #!/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
    output:
    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

  • 相关阅读:
    cocos2d-x 3.0rc1 编译cpp-testsproject
    [wxWidgets]_[0基础]_[不常见但有用的类wxStandardPaths]
    教你摆脱低级程序猿 项目中cocopads的安装使用
    Android使用代码模拟HOME键的功能
    UVA 1508
    asp.net mvc5 安装
    Java_并发线程_Semaphore、CountDownLatch、CyclicBarrier、Exchanger
    crm操作产品实体
    BZOJ 3172 [Tjoi2013]单词 AC自己主动机(fail树)
    ADO与ADO.Net
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3144975.html
Copyright © 2011-2022 走看看