一.判斷的命令和方式
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