如何在 Bash 中判断变量是否为空

发布于 2024-09-05 16:54:24 字数 26 浏览 7 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

帅的被狗咬 2024-09-12 16:54:24

在 Bash 中,至少可以使用以下命令测试如果 $var 为空

if [[ -z "$var" ]]; then
   # $var is empty, do what you want
fi

命令 man test 是你的朋友。

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

if [[ -z "$var" ]]; then
   # $var is empty, do what you want
fi

The command man test is your friend.

高跟鞋的旋律 2024-09-12 16:54:24

假设重击:

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

Presuming Bash:

var=""
if [ -n "$var" ]; then
    echo "not empty"
else
    echo "empty"
fi
暗恋未遂 2024-09-12 16:54:24

我还看到

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

这显然非常强大并且独立于 shell。

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

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.

浊酒尽余欢 2024-09-12 16:54:24
if [ ${foo:+1} ]
then
    echo "yes"
fi

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

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

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

鸩远一方 2024-09-12 16:54:24
if [[ "$variable" == "" ]] ...
if [[ "$variable" == "" ]] ...
红墙和绿瓦 2024-09-12 16:54:24
[ "$variable" ] || echo empty
: ${variable="value_to_set_if_unset"}
[ "$variable" ] || echo empty
: ${variable="value_to_set_if_unset"}
眼泪淡了忧伤 2024-09-12 16:54:24

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

但我在 PHP 编程一段时间后才来到这里,我实际上是在寻找像 PHP 中的空函数一样在 Bash shell 中工作的检查。

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

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

根据 PHP 手册

变量被认为是空的,如果它不存在或者它的值为以下之一:

  • ""(空字符串)
  • 0(0 作为整数)
  • 0.0(0 作为浮点数)
  • “0”(0 作为字符串)
  • an空数组
  • 声明了一个变量,但没有值

当然,nullfalse 情况在 bash 中无法转换,因此它们被省略。

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 "" ) ]]
}

使用示例:

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

演示:
以下片段:

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

输出:

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

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

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 I was actually searching for 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.

唔猫 2024-09-12 16:54:24

如果变量未设置或设置为空字符串 (""),则返回 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

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

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
殊姿 2024-09-12 16:54:24

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

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

结果:

set and non-empty
set and empty
unset

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

rm -rf $dir

此内容以及“严格模式”的其他最佳实践>。

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.

你怎么敢 2024-09-12 16:54:24

检查变量 v 是否未设置

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

To check if variable v is not set

if [ "$v" == "" ]; then
   echo "v not set"
fi
带上头具痛哭 2024-09-12 16:54:24

如果您更喜欢使用测试

test -z $AA && echo empty || echo not-empty
AA=aa; test -z $AA && echo empty || echo not-empty
AA=aa; test ! -z $AA && echo empty || echo not-empty

If you prefer to use test:

test -z $AA && echo empty || echo not-empty
AA=aa; test -z $AA && echo empty || echo not-empty
AA=aa; test ! -z $AA && echo empty || echo not-empty
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文