bash 如何在Bash中查找变量是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3061036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:22:28  来源:igfitidea点击:

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

bashshellis-empty

提问by Tree

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

如何检查 Bash 中的变量是否为空?

回答by Jay

In Bash at least the following command tests if $var is empty:

在 Bash 中,至少以下命令测试$var 是否为空

if [[ -z "$var" ]]; then
   # Do what you want
fi

The command man testis your friend.

命令man test是你的朋友。

回答by ChristopheD

Presuming Bash:

假设 Bash:

var=""

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

回答by Daniel Andersson

I have also seen

我也见过

if [ "x$variable" = "x" ]; then ...

which is obviously very robust and shell independent.

这显然非常健壮且独立于外壳。

Also, there is a difference between "empty" and "unset". See How to tell if a string is not defined in a Bash shell script.

此外,“空”和“未设置”之间也有区别。请参阅如何判断字符串是否未在 Bash shell 脚本中定义

回答by alexli

if [ ${foo:+1} ]
then
    echo "yes"
fi

prints yesif the variable is set. ${foo:+1}will return 1 when the variable is set, otherwise it will return empty string.

yes如果设置了变量,则打印。${foo:+1}设置变量时将返回1,否则将返回空字符串。

回答by Amardeep AC9MF

if [[ "$variable" == "" ]] ...

回答by pixelbeat

[ "$variable" ] || echo empty
: ${variable="value_to_set_if_unset"}

回答by 3kstc

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

true如果变量未设置或设置为空字符串 (""),这将返回。

if [ -z "$MyVar" ]
then
   echo "The variable MyVar has nothing in it."
elif ! [ -z "$MyVar" ]
then
   echo "The variable MyVar has something in it."
fi

回答by Luca Borrione

The questionasks how to check if a variable is an empty stringand the best answers are already given for that.

问题询问如何检查变量是否为空字符串,并且已经为此给出了最佳答案。

But I landed here after a period passed programming in PHP, and I was actually searching for a check like the empty function in PHPworking in a Bash shell.

但是我在通过 PHP 编程一段时间后来到这里,我实际上是在寻找一个检查,比如在 Bash shell 中工作的PHP 中空函数

After reading the answers I realized I was not thinking properly in Bash, but anyhow in that moment a function like emptyin PHP would have been soooo handy in my Bash code.

阅读答案后,我意识到我在 Bash 中没有正确思考,但无论如何,在那一刻,像PHP 中的empty这样的函数在我的 Bash 代码中会非常方便。

As I think this can happen to others, I decided to convert the PHP empty function in Bash.

因为我认为这可能发生在其他人身上,所以我决定在 Bash 中转换 PHP 空函数。

According to the PHP manual:

根据PHP 手册

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
  • ""(空字符串)
  • 0(0 作为整数)
  • 0.0(0 作为浮点数)
  • “0”(0 作为字符串)
  • 空数组
  • 声明的变量,但没有值

Of course the nulland falsecases cannot be converted in bash, so they are omitted.

当然nullfalse的情况在bash中是不能转换的,所以省略了。

function empty
{
    local var=""

    # 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.

话虽如此,在 Bash 逻辑中,此函数中的零检查可能会导致附带问题,恕我直言,任何使用此函数的人都应该评估这种风险,并可能决定切断这些检查,只留下第一个。

回答by dimid

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

您可能想要区分未设置变量和已设置且为空的变量:

is_empty() {
    local var_name=""
    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 -uwhich will cause an error when reading unset variables, this can save you from disasters such as

顺便说一句,我建议使用set -uwhich 在读取未设置的变量时会导致错误,这可以使您免于灾难,例如

rm -rf $dir

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

您可以在此处阅读有关“严格模式”的此和其他最佳实践的信息

回答by smishra

To check if variable v is not set

检查变量 v 是否未设置

if [ "$v" == "" ]; then
   echo "v not set"
fi