bash Shell脚本:如何检查变量是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48261038/
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-18 16:46:22  来源:igfitidea点击:

Shell Script : How to check if variable is null or no

stringbashshellis-empty

提问by TheRight

I want to check if variable is null or no.

我想检查变量是否为空。

My code is :

我的代码是:

    list_Data="2018-01-15 10:00:00.000|zQfrkkiabiPZ||04|
            2018-01-15 10:00:00.000|zQgKLANvbRWg||04|
            2018-01-15 10:00:00.000|zQgTEbJjWGjf||01|
            2018-01-15 10:00:00.000|zQgwF1YJLnAT||01|"

    echo "list_Data"

    if [[ -z "list_Data" ]]
    then
    echo "not Empty"
    else
    echo "empty"
    fi

The Output is :

输出是:

2018-01-15 10:00:00.000|zQfrkkiabiPZ||04|
2018-01-15 10:00:00.000|zQgKLANvbRWg||04|
2018-01-15 10:00:00.000|zQgTEbJjWGjf||01|
2018-01-15 10:00:00.000|zQgwF1YJLnAT||01|
empty

The problem that the varible contain values but i have always empty message please help.

变量包含值但我总是有空消息的问题请帮助。

回答by RavinderSingh13

Try following, you should change from -zto -nas follows and add $to your variable too.

尝试以下,您应该从-z改为-n如下并添加$到您的变量中。

if [[ -n "$list_Data" ]]
then
    echo "not Empty"
else
    echo "empty"
fi

Explanation:From man testpage as follows(It checks if a variable is having any value or not. If it has any value then condition is TRUE, if not then it is FALSE.)

说明:man test页面如下(它检查一个变量是否有任何值。如果有任何值,则条件为真,如果没有,则为假。)

   -n STRING
          the length of STRING is nonzero
   -n STRING
          the length of STRING is nonzero

回答by Alfe

if [[ -z "$list_Data" ]]
then
  echo "Empty"
else
  echo "Not empty"
fi

Try it like this. (Added $and switched cases.)

像这样试试。(添加$和切换案例。)