linux 中条件判断关键字 -s 、 -z 和 -n

 

001、 -s file:文件存在而且文件不为空,则为真,否则为假

(base) [root@pc1 test01]# ls
a.txt  b.txt
(base) [root@pc1 test01]# ll -h    ## 两个侧式文件,a.txt不为空,b.txt则为空
total 4.0K
-rw-r--r--. 1 root root 10 Oct  6 19:40 a.txt
-rw-r--r--. 1 root root  0 Oct  6 19:40 b.txt
(base) [root@pc1 test01]# [ -s a.txt ]       ## a.txt存在,而且不为空,因此为真
(base) [root@pc1 test01]# echo $?
0
(base) [root@pc1 test01]# [ -s c.txt ]       ## c.txt不存在,因为为假
(base) [root@pc1 test01]# echo $?
1
(base) [root@pc1 test01]# [ -s b.txt ]       ## b.txt存在,但是b.txt为空,因此为假
(base) [root@pc1 test01]# echo $?
1

 

002、-z string : string的长度为0 则为真

[root@pc1 test01]# ls
[root@pc1 test01]# a=100     
[root@pc1 test01]# echo $a               ##测试字符串
100
[root@pc1 test01]# echo $b

[root@pc1 test01]# [ -z "$a" ]          ## a长度不为0,为假
[root@pc1 test01]# echo $?
1
[root@pc1 test01]# [ -z "$b" ]          ## b的长度为0, 为真
[root@pc1 test01]# echo $?
0

 

003、-n: string的长度不为0则为真,否则为假

a、

[root@pc1 test01]# echo $a
100
[root@pc1 test01]# echo $b

[root@pc1 test01]# [ -n "$a" ]       ## a长度不为0, 因此为真
[root@pc1 test01]# echo $?
0
[root@pc1 test01]# [ -n "$b" ]       ## b长度为0, 为此为假
[root@pc1 test01]# echo $?
1

 

b、等价于如下形式

[root@pc1 test01]# ls
[root@pc1 test01]# a=100
[root@pc1 test01]# echo $a
100
[root@pc1 test01]# echo $b

[root@pc1 test01]# [ "$a" ]       ##a 的长度不为0, 因此为真
[root@pc1 test01]# echo $?
0
[root@pc1 test01]# [ "$b" ]      ##  b的长度为0, 因此为假
[root@pc1 test01]# echo $?
1

 

 

posted @ 2023-10-06 19:44  小鲨鱼2018  阅读(712)  评论(0编辑  收藏  举报