文章目录
Shell 编程----条件语句
一:条件测试
1.1:文件测试与整数测试
1.1.1:文件测试
-
test 命令
测试表达式是否成立,若成立返回0,否则返回其他数值.
格式1: [test 条件表达式]
格式2: [ 条件表达式 ]
注意:格式2中表达式与中括号之间要有空格,否则语法错误.
-
文件测试
[ 操作符 文件或目录 ]
常用的测试操作符
常见的测试操作符 解释 -d 测试是否为目录(directory) -e 测试目录或文件是否存在(Exist) -f 测试是否为文件(File) -r 测试当前用户是否有权限读取(Read) -w 测试当前用户是否有权限写入(Write) -x 测试当前用户是否有权限执行(eXcute) 注意: 测试文件推荐用绝对路径
[root@shell ~]# touch abc.txt [root@shell ~]# test -f abc.txt [root@shell ~]# echo $? 0 [root@shell ~]# test -d abc.txt [root@shell ~]# echo $? 1 [root@shell ~]# [-d abc.txt] bash: [-d: 未找到命令... '注意中括号要有空格,要不然报错' [root@shell ~]# [ -d abc.txt ] [root@shell ~]# echo $? 1 [root@shell ~]# [ -f abc.txt ] [root@shell ~]# echo $? 0
[root@shell ~]# [ -d /dev/cdrom ] [root@shell ~]# echo $? 1 [root@shell ~]# [ -f /dev/cdrom ] [root@shell ~]# echo $? 1 [root@shell ~]# [ -e /dev/cdrom ] [root@shell ~]# echo $? 0 [root@shell ~]# [ -e /dev/cdrom ]&& echo "yes" yes [root@shell ~]# [ -d /dev/cdrom ]&& echo "yes" [root@shell ~]# [ -f /dev/cdrom ]&& echo "yes" '注意&& 前面成立继续执行后面内容 '&&前面不成立不执行后面的内容'
1.1.2: 整数值比较
-
[ 整数1 操作符 整数2 ]
-
操作符 解释 -eq 等于(Equal) -ne 不等于(Not Equal) -gt 大于(Greater Than) -lt 小于(Lesser Than) -le 小于或等于(Lesser or Equal -ge 大于或等于(Greater or Equal) -
[root@shell ~]# [ 55 -gt 80 ] && echo "yes" [root@shell ~]# [ 80 = 80 ] && echo "yes" yes [root@shell ~]# [ 80 == 80 ] && echo "yes" yes [root@shell ~]# [root@shell ~]# [ 'zhangsan' == 'zhangsan' ] && echo yes yes [root@shell ~]# [ 'zhangsan' -eq 'zhangsan' ] && echo yes bash: [: zhangsan: 期待整数表达式 [root@shell ~]# [ 'zhangsan' == 'zhang' ] && echo yes [root@shell ~]# [ ! 'zhangsan' == 'zhang' ] && echo 'yes'
[root@shell ~]