Shell_06_判断表达式

2019-12-22  本文已影响0人  热爱_生活

test

image

示例:

$ touch a.txt
$ test -e a.txt;echo $?
0                             # 测试成功,命令返回值为 0

$ test -e s.txt;echo $?
1                             # 测试失败,命令返回值为 非 0

$ test -f a.txt;echo $?
0

$ test -d a.txt;echo $?
1


image

示例:

$ test -r a.txt; echo $?
0

$ test -x a.txt; echo $?
1

$ test -w a.txt; echo $?
0

$ test -u a.txt; echo $?     # 判断 a.txt 文件是否具有 SUID 属性
1

$ cat a.txt                        # 查看 a.txt ,此文件内容为空

$ test -s a.txt; echo $?    # 判断 a.txt 文件中有内容
1                                      # 命令返回值为 1 ,说明文件中没有内容

$ echo "123" > a.txt

$ test -s a.txt; echo $?
0


image

示例:

$ touch b.txt

$ ls -l a.txt
-rw-r--r--  1 shark  staff  4 12 17 22:59 a.txt

$ ls -l b.txt
-rw-r--r--  1 shark  staff  0 12 17 23:05 b.txt

$ test a.txt -nt b.txt; echo $?  # 判断 a.txt 是否比 b.txt 新
1                                            # 返回 1, 表示判断表达式不成立

$ test b.txt -nt a.txt; echo $?
0

image
$ test a.txt -ef a-hard.txt; echo $?
0


image

示例:

$ test 10 -eq 20; echo $?
1

$ n1=10

$ n2=20

$ test $n1 -eq $n2; echo $?
1

$ test $n1 -lt $n2; echo $?
0

$ test $n1 -ne  $n2; echo $?
0


image

注意:
这里的 string 可以是实际的字符串,也可以是一个变量
这里说的字符串是否为 0 的意思是 字符串的长度是否为 0

示例

$ test   -z  ''; echo $?      # 空字符串
0

$ test  -z  ' '; echo $?      # 含有一个空格的字符串
1

$ test  !  -z ' '; echo $?   # 判断含有一个空格的字符串,其长度为非 0 的字符串, 空格也算是字符串。
0

$ test -z ${name}; echo $?   # 变量未定义,shell 中认为其长度为 0
0

$ name=shark

$ test -z ${name}; echo $?
1

$ age=''                               # 定义变量,并且赋值为空字符串

$ test  -z  ${age}; echo $?    # shell 中,被赋值为空字符串的变量长度也为 0
0

注意:

再次强调一下, 在 shell 中,以下两种情况,变量的长度均视为 0

  • 1.变量未定义
    1. 变量定义了,但赋值为空字符串,比如 a='' , b=""
[root@kube-master script]# name=shark
[root@kube-master script]# age=shark
[root@kube-master script]# test $name == $age ;echo $?
0
[root@kube-master script]# test $name != $age ;echo $?
1
[root@kube-master script]#


image

示例

image

判断符号 []

[ -z "${HOME}" ] ; echo $?

必须要注意中括号的两端需要有空白字符来分隔喔! 假设我空白键使用“□”符号来表示,那么,在这些地方你都需要有空白键:

image

错误示范

# 定义变量
name="shark ops"

# 开始测试值是否相等
[ ${name} == "xiguatian" ]

会报如下错误信息:

bash: [: too many arguments

之前的错误写法 [ ${name} == "xiguatian" ] 的,会变成这样 [ shark ops == "xiguatian" ]

正确写法应该写成这样 [ "${name}" == "xiguatian" ] 的, 会变成这样 [ "shark ops" == "xiguatian" ]

上一篇 下一篇

猜你喜欢

热点阅读