您的位置:首页 > 运维架构 > Shell

How to find variable is empty in shell script

2013-06-19 14:27 323 查看
(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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  How to find variable