一.判断的命令和方式
test 条件表达式
[ 条件表达式 ] 注意条件表达式两边有空格
[[ 条件表达式 ]] 支持正则表达式
[root@localhost mysql]# test -e /etc/ [root@localhost mysql]# echo $0 -bash [root@localhost mysql]# echo $? 0 [root@localhost mysql]# test -e /etc/ [root@localhost mysql]# echo $? 0 [root@localhost mysql]# test -e /aaaaaaa [root@localhost mysql]# echo $? 1 [root@localhost mysql]# [ -e /tmp ] [root@localhost mysql]# echo $? 0 [root@localhost mysql]# [ -e /aaaaaa ] [root@localhost mysql]# echo $? 1
二.文件属性相关判断
-e 文件(包括目录)是否存在
-d 是否是目录
-f 是否是普通文件
-L 是否是链接文件
-S 是否是socket文件
-p 是否是管道文件
-s 文件大小是否存在并且为非空文件,无法判断非空目录;注意存在且非空才返回true
三.文件权限相关的判断
-r 当前用户是否可读
-w 当前用户是否可写
-x 当前用户是否可执行
-u 是否有suid(权限9位的前3位里是否有s位)
-g 是否sgid(权限9位的中间3位里是否有s位)
-k 是否有t位(权限9位的后3位里是否有t位)
测试时需要注意最好不要使用root用户,因为root为管理员,他有所有权限
四.文件新旧比较
file1 -nt file2 file1是否比file2新
file1 -ot file2 file1是否比file2旧
file -ef file2 file1是否和file2指向同一个inode
五.数字的比较
-eq 等于
-ne 不等于
-gt 大于
-lt 小于
-ge 大于等于
-le 小于等于
[root@server shell02]# cat 8.sh #!/bin/bash /etc/init.d/sshd status if [ $? -eq 0 ] then echo "sshd is already started." port=$(netstat -ntlp|grep sshd|grep -v "grep"|tr -s " "|cut -d " " -f 4|grep ^:::|cut -d: -f 4) echo "sshd port is $port." fi [root@server shell02]# sh 8.sh openssh-daemon (pid 1492) is running... sshd is already started. sshd port is 22.
六.字符串相关的判断
-z 字符串是否为空
-n 字符串是否不为空
str1 = str2 是否相等
str1 != str2 是否不相等
[root@server shell02]# cat 9.sh #!bin /bash read -p "pls input the file path:" file_path if [ -e $file_path ] then file_type=$(ls -ld $file_path|cut -c1) if [ $file_type = - ] then echo "$file_path is a text file." elif [ $file_type = d ] then echo "$file_path is a directory." elif [ $file_type = b ] then echo "$file_path is a black file." elif [ $file_type = c ] then echo "$file_path is a character file." elif [ $file_type = p ] then echo "$file_path is a pipe file." elif [ $file_type = l ] then echo "$file_path is a link file." elif [ $file_type = s ] then echo "$file_path is a socket file." fi else echo "$file_path is not exist" fi [root@server shell02]# sh 9.sh pls input the file path:/etc /etc is a directory. [root@server shell02]# sh 9.sh pls input the file path:/etc/hosts /etc/hosts is a text file.
七.逻辑连接
-a 且,和 表示连个条件同时满足
-o 或,两个条件满足一个即可
expression1 && expression2 expression1为真才执行expression2
expression1 || expression2 expression1为假才执行expression2
expression1 ;expression2 不管expression1执行是否正确,expression2都会执行
[root@server shell02]# cat 13.sh #!/bin/bash read -p "pls input the year(xxxx):" year [ $[year%4] -eq 0 -a $[year%100] -ne 0 -o $[year%400] -eq 0 ] && echo yes #echo $result [root@server shell02]# sh 13.sh pls input the year(xxxx):2000 yes [root@server shell02]# sh 13.sh pls input the year(xxxx):2008 yes [root@server shell02]# sh 13.sh pls input the year(xxxx):2018