判断是否空串(或者未定义)
格式1:test -z "$STR"
格式2:[ -z "$STR" ]
注:test是[]的同义词。注意加上引号,否则有可能报错。
格式3:test "$STR" == ""
格式4:[ "$STR" == "" ]
格式5:test "$STR" = ""
格式6:[ "$STR" = "" ]
注:==等同于=。
格式7:[[ "$STR" = "" ]]
格式8:[[ $STR = "" ]]
格式9:[[ "$STR" == "" ]]
格式10:[[ $STR == "" ]]
格式11:[[ ! $STR ]]
注:[[是Bash关键字,其中的变量引用不需要加双引号。
[root@jfht ~]# if test -z "$STR"; then echo "STR is null or empty"; fi
STR is null or empty
[root@jfht ~]# if [ -z "$STR" ]; then echo "STR is null or empty"; fi
STR is null or empty
[root@jfht ~]# if test "$STR" == ""; then echo "STR is null or empty"; fi
STR is null or empty
[root@jfht ~]# if [ "$STR" == "" ]; then echo "STR is null or empty"; fi
STR is null or empty
[root@jfht ~]# if test "$STR" = ""; then echo "STR is null or empty"; fi
STR is null or empty
[root@jfht ~]# if [ "$STR" = "" ]; then echo "STR is null or empty"; fi
STR is null or empty
[root@jfht ~]# if [[ "$STR" = "" ]]; then echo "STR is null or empty"; fi
STR is null or empty
[root@jfht ~]# if [[ $STR = "" ]]; then echo "STR is null or empty"; fi
STR is null or empty
[root@jfht ~]# if [[ ! $STR ]]; then echo "STR is null or empty"; fi
STR is null or empty
[root@jfht ~]#
判断是否非空串
格式1:test "$STR"
格式2:[ "$STR" ]
格式3:test -n "$STR"
格式4:[ -n "$STR" ]
格式5:test ! -z "$STR"
格式6:[ ! -z "$STR" ]
格式7:test "$STR" != ""
格式8:[ "$STR" != "" ]
格式9:[[ "$STR" ]]
格式10:[[ $STR ]]
the length of STRING is nonzero
STRING
equivalent to -n STRING
-z STRING
the length of STRING is zero
判断变量是否已定义(声明)
格式1:if declare -p VAR; then do_something; fi
格式2:declare -p VAR && do_something
在Bash中typeset命令等同于declare命令。
格式3:if [ "${VAR+YES}" ]; then do_something; fi
格式4:[ "${VAR+YES}" ] && do_something
${VAR+YES}表示如果VAR没有定义则返回YES,否则返回空
[root@jfht ~]# if declare -p VAR; then echo "VAR defined"; fi
-bash: declare: VAR: not found
[root@jfht ~]# declare -p VAR && echo "VAR defined"
-bash: declare: VAR: not found
[root@jfht ~]# if [ "${VAR+YES}" ]; then echo "VAR defined"; fi
[root@jfht ~]# [ "${VAR+YES}" ] &&echo "VAR defined"
[root@jfht ~]#
[root@jfht ~]# VAR=
[root@jfht ~]# if declare -p VAR; then echo "VAR defined"; fi
declare -- VAR=""
VAR defined
[root@jfht ~]# declare -p VAR && echo "VAR defined"
declare -- VAR=""
VAR defined
[root@jfht ~]# if [ "${VAR+YES}" ]; then echo "VAR defined"; fi
VAR defined
[root@jfht ~]# [ "${VAR+YES}" ] &&echo "VAR defined"
VAR defined
[root@jfht ~]#
判断变量没有定义(声明)
格式1:if [ ! "${VAR+YES}" ]; then do_something; fi
格式2:[ ! "${VAR+YES}" ] && do_something
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/22418990/viewspace-732804/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/22418990/viewspace-732804/