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 @   小鲨鱼2018  阅读(1018)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2022-10-06 shell 脚本中 set -e选项的作用
2022-10-06 How to install CPAN modules
2022-10-06 Can't exec "mysql_config": No such file or directory at Makefile.PL line 89.
2022-10-06 perl包的安装
2021-10-06 格式工厂合并视频和音频文件
2021-10-06 IDM下载B站视频多个文件,视频、音频分开如何处理
2021-10-06 截图快捷键
点击右上角即可分享
微信分享提示