KSH 脚本:-z 和 -a

KSH scripting: -z and -a

我有以下条件:

 if [ ! -z $DateC -a "$DateC"=="$DateJ" ] 

如果想知道 -z 和 -a 是什么意思。我不明白这个条件验证了什么。我在网上搜索了 -a 和 -z 但我真的不明白它的作用。有什么帮助吗?

为此检查 man test

   -z STRING
          the length of STRING is zero
   EXPRESSION1 -a EXPRESSION2
          both EXPRESSION1 and EXPRESSION2 are true

所以这会检查 $DateC 的长度是否不为零并且 $DateC$DateJ 是否相等。

if [ ! -z $DateC -a "$DateC"=="$DateJ" ] 
#      ^^^^^^^^^ ^^
#         |     AND
#         |
#      length of string is zero
#
#    ^^^^^^^^^^^^^^^^^^^^^^^^^^
#    length of string is NOT zero

看例子:

$ r=hello
$ s=hello
$ [ "$r"=="$s" ] && echo "yes" || echo "no"
yes

另一种情况:

$ t=""
$ if [ ! -z "$t" -a "$r"=="$s" ]; then echo "yes"; else echo "no"; fi
no
$ t=a
$ if [ ! -z "$t" -a "$r"=="$s" ]; then echo "yes"; else echo "no"; fi
yes

最后,

Note that POSIX recommends the use of && and || with the single bracket notation over -a and -o, so if you are writing portable code go for the first notation, otherwise the second and skip the third, especially since it can get awkward and hard to read if you need to group expressions. – Adrian Frühwirth (source)