随笔 - 133  文章 - 0  评论 - 0  阅读 - 37474

shell条件测试2

脚本中经常进行条件测试,用的最多的,都是中括号[ ]
test和[ ]的昨天是一样
注意的点:中括号,前后的空格必须。
[ -n "$filename" ]

注意,在条件测试中使用变量,必须添加双引号
双中括号 [[条件表达式]]

[root@localhost jay]# su - jay
上一次登录:五 519 16:40:21 CST 2023pts/0 上
[jay@localhost ~]$ ls
zz.txt
[jay@localhost ~]$ touch 1.txt
[jay@localhost ~]$ [ -f "hello.txt" ] && echo "已存在" || touch "hello.txt" && echo "创建成功"
创建成功
[jay@localhost ~]$ ls
1.txt  hello.txt  zz.txt
[jay@localhost ~]$ ll
总用量 0
-rw-rw-r--. 1 jay jay 0 519 16:45 1.txt
-rw-rw-r--. 1 jay jay 0 519 16:46 hello.txt
-rw-rw-r--. 1 jay jay 0 519 16:44 zz.txt
[jay@localhost ~]$ chmod 0 hello.txt 
[jay@localhost ~]$ ls
1.txt  hello.txt  zz.txt
[jay@localhost ~]$ cat hello.txt 
cat: hello.txt: 权限不够
[jay@localhost ~]$ [[ -r "hello.txt" ]] && cat hello.txt || echo "没有权限看不了"
没有权限看不了

变量测试
把字符串信息,写入到变量中
对变量测试,必须加双引号


字符串比较测试

比较两个字符串的值,是否相等,不等这样的情况


注意
对于字符串变量的比较
一定要记住给变量添加双引号
使用等于号的值判断,左右两边也必须有空格

在中括号中,以及test中数值测试的用法
在中括号中,使用数学比较符合,请添加转义符号


在test和[]语法中,支持-eq此类写法,以及支持 > < = !=
在双中括号中,就不需要转义符号了

在工作中,用的最多的就是单中括号,双括号属于特殊场景的扩展语法
并且 双中括号也是 支持 -eq -lt < > =

posted on   sprr  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
历史上的今天:
2021-05-19 软件包管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示