shell_条件判断_[]中括号
条件测试
条件测试[]中括号
脚本中经常进行条件测试,用的最多的,都是中括号[ ]
test 和[] 中括号的作用是意义的;只是 中括号[],前后的空格必须有
注意!!!
中括号[],前后的空格必须有
在条件测试中使用变量,必须添加双引号
[ -n "${filename}" ]
[root@localhost tmp]# [ -f "$filename1" ]&& echo ok || echo no
ok
[root@localhost tmp]# rm -f demo1.sh
[root@localhost tmp]# [ -f "$filename1" ]&& echo ok || echo no
no
[root@localhost tmp]# echo $filename1
demo1.sh
[root@localhost tmp]# touch $filename1
[root@localhost tmp]# [ -f "$filename1" ]&& echo ok || echo no
ok
[root@localhost tmp]# [ -f $filename1 ]&& echo ok || echo no ####自己感觉没加引号也能输出,但还是加上吧
ok
[root@localhost tmp]# rm -f demo1.sh
[root@localhost tmp]# [ -f $filename1 ]&& echo ok || echo no
no
[root@localhost tmp]#
###-a 多重判断and的意思
##-r 验证可读的属性与前面的条件判断参数都通用
[mrxu@localhost myshell]$ [ -r "mytest01.sh" -a -e "mytest01.sh" ]&& echo "read ok" || echo "read no"
read ok
[mrxu@localhost myshell]$ chmod 0 mytest01.sh
[mrxu@localhost myshell]$ [ -r "mytest01.sh" -a -e "mytest01.sh" ]&& echo "read ok" || echo "read no"
read no
[mrxu@localhost myshell]$ [ -r "mytest01xxx.sh" -a -e "mytest01.sh" ]&& echo "read ok" || echo "read no" ###改变第 一个条件让他false
read no
条件测试[[]]双中小括号
[[条件表达式]]
验证文件是否有权限
注意:root是超级管理员,对于权限学习需要切换用户
####双中括号与中括号用法一致,但是感觉没法多重判断,会报错
[mrxu@localhost myshell]$
[mrxu@localhost myshell]$ [[ -r "mytest01xxx.sh" ]] && echo "read ok" || echo "read no"
[mrxu@localhost myshell]$ [[ -r "mytest01xxx.sh" -a -e "mytest01.sh" ]] && echo "read ok" || echo "read no"
-bash: 条件表达式中有语法错误
-bash: `-a' 附近有语法错误
[mrxu@localhost myshell]$
######
[mrxu@localhost myshell]$ chmod a-r mytest02.sh
[mrxu@localhost myshell]$ [ -r "mytest02.sh" ]&& cat mytest02.sh ||echo "对不起你没读取权限"
对不起你没读取权限
[mrxu@localhost myshell]$ chmod a+r mytest02.sh
[mrxu@localhost myshell]$ [ -r "mytest02.sh" ]&& cat mytest02.sh ||echo "对不起你没读取权限"
[mrxu@localhost myshell]$ [ -w "mytest02.sh" ]&& echo "来阿,快活阿,反正就这个雕样" >mytest02.sh ||echo "对不起你没写入权限"
对不起你没写入权限
[mrxu@localhost myshell]$ chmod a+w mytest02.sh
[mrxu@localhost myshell]$ [ -w "mytest02.sh" ]&& echo "来阿,快活阿,反正就这个雕样" >mytest02.sh ||echo "对不起你没写入权限"
[mrxu@localhost myshell]$ [ -r "mytest02.sh" ]&& cat mytest02.sh ||echo "对不起你没读取权限"
来阿,快活阿,反正就这个雕样
[mrxu@localhost myshell]$ [[ -w "mytest02.sh" ]]&& echo "来阿,快活阿,反正就这个雕样2" >>mytest02.sh ||echo "对不起你没写入权限"
[mrxu@localhost myshell]$ [[ -r "mytest02.sh" ]]&& cat mytest02.sh ||echo "对不起你没读取权限"
来阿,快活阿,反正就这个雕样
来阿,快活阿,反正就这个雕样2
[mrxu@localhost myshell]$
分类:
shell实战1
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!