Bash Shell找出变量是否具有NULL值
时间:2020-01-09 10:37:26 来源:igfitidea点击:
如何在Linux或Unix Shell脚本中检查NULL值?
您可以在Bash Shell脚本中快速测试空变量或空变量。
您需要将-z或-n选项传递给测试命令或if命令,或使用条件表达式。
该页面显示了如何使用test命令找出bash shell变量是否为NULL值。
要确定bash变量是否为null:
- 如果未设置bash变量或将其设置为null(空)字符串,则返回true:
if [ -z "$var" ]; then echo "NULL"; else echo "Not NULL"; fi
- 查找bash变量是否设置为NULL的另一个选项:
[ -z "$var" ] && echo "NULL"
- 确定bash变量是否为NULL:
[[ ! -z "$var" ]] && echo "Not NULL" || echo "NULL"
Bash Shell找出变量是否具有NULL值
让我们详细查看测试命令语法和示例。
if命令的语法如下:
my_var="theitroad" if [ -z "$my_var" ] then echo "$my_var is NULL" else echo "$my_var is NOT NULL" fi
或者
my_var="" if test -z "$my_var" then echo "$my_var is NULL" else echo "$my_var is NOT NULL" fi
检查bash shell变量是否为NULL的另一种选择
[ -z "$my_var" ] && echo "NULL" [ -z "$my_var" ] && echo "NULL" || echo "Not NULL"
或者
[[ -z "$my_var" ]] && echo "NULL" [[ -z "$my_var" ]] && echo "NULL" || echo "Not NULL"
或者
## Check if $my_var is NULL using ! i.e. check if expr is false ## [ ! -z "$my_var" ] || echo "NULL" [ ! -z "$my_var" ] && echo "Not NULL" || echo "NULL" [[ ! -z "$my_var" ]] || echo "NULL" [[ ! -z "$my_var" ]] && echo "Not NULL" || echo "NULL"
如果在Unix上有条件,如何在shell中查找NULL值
如果STRING的长度非零,则-n返回TRUE。
例如:
#!/bin/bash var="" if [ ! -n "$var" ] then echo "#!/bin/bash # Purpose - Test for NULL/empty shell var # Author - Hyman Gite {htttps://www.theitroad.local} under GPL 2.0+ DEMO="theitroad.local" HINT="" ##################################### # Do three possibilities for $DEMO ## ##################################### for i in 1 2 3 do case $i in 1) DEMO="theitroad.com"; HINT="value set";; 2) DEMO=""; HINT="value set to empty string";; 3) unset DEMO; HINT="$DEMO unset";; esac ############################################### # Update user with actual values and action # $DEMO set to a non-empty string (1) # $DEMO set to the empty string (2) # $DEMO can be unset (3) ################################################ echo "*** Current value of $DEMO is '$DEMO' ($HINT) ***" ######################################################################## ## Determine if a bash variable is NULL, set, unset or not set at ALL ## ######################################################################## if [ -z "${DEMO}" ]; then echo "DEMO is unset or set to the empty string" fi if [ -z "${DEMO+set}" ]; then echo "DEMO is unset" fi if [ -z "${DEMO-unset}" ]; then echo "DEMO is set to the empty string" fi if [ -n "${DEMO}" ]; then echo "DEMO is set to a non-empty string" fi if [ -n "${DEMO+set}" ]; then echo "DEMO is set, possibly to the empty string" fi if [ -n "${DEMO-unset}" ]; then echo "DEMO is either unset or set to a non-empty string" fi done- Error $var not set or NULL" else echo "$var set and now starting ##代码## shell script..." fi
示例:确定bash变量是否为NULL
以下shell脚本显示了基于bash/sh/posix的shell的各种可能性:
##代码##