shell_条件判断_[]中括号

发布时间 2023-10-10 10:41:55作者: WeChat2834
条件测试
条件测试[]中括号

脚本中经常进行条件测试,用的最多的,都是中括号[ ]

test 和[] 中括号的作用是意义的;只是 中括号[],前后的空格必须有

注意!!!

  1. 中括号[],前后的空格必须有

  2. 在条件测试中使用变量,必须添加双引号

[ -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]$