Null & empty string comparison in Bash [duplicate]

2019-03-10 16:37发布

This question already has an answer here:

I don't set any values for $pass_tc11; so it is returning null while echoing. How to compare it in if clause?

Here is my code. I don't want "Hi" to be printed...

-bash-3.00$ echo $pass_tc11

-bash-3.00$ if [ "pass_tc11" != "" ]; then
> echo "hi"
> fi
hi
-bash-3.00$

标签: bash shell
2条回答
唯我独甜
2楼-- · 2019-03-10 17:13

First of all, note you are not using the variable correctly:

if [ "pass_tc11" != "" ]; then
#     ^
#     missing $

Anyway, to check if a variable is empty or not you can use -z --> the string is empty:

if [ ! -z "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

or -n --> the length is non-zero:

if [ -n "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

From man test:

-z STRING

the length of STRING is zero

-n STRING

the length of STRING is nonzero

Samples:

$ [ ! -z "$var" ] && echo "yes"
$

$ var=""
$ [ ! -z "$var" ] && echo "yes"
$

$ var="a"
$ [ ! -z "$var" ] && echo "yes"
yes

$ var="a"
$ [ -n "$var" ] && echo "yes"
yes
查看更多
放荡不羁爱自由
3楼-- · 2019-03-10 17:29

fedorqui has a working solution but there is another way to do the same thing.

Chock if a variable is set

#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
    echo 'No, I am not!';
fi

Or to verify that a variable is empty

#!/bin/bash      
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
    echo 'Yes I am!';
fi

tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

查看更多
登录 后发表回答