20.5 shell腳本中的邏輯判斷
格式1:if 條件 ; then 語句; fi
格式2:if 條件; then 語句; else 語句; fi
格式3:if …; then … ;elif …; then …; else …; fi
邏輯判斷表達式:if [ $a -gt $b ]; if [ $a -lt 5 ]; if [ $b -eq 10 ]等 , 注意處處都是空格
-gt (>); -lt(<); -ge(>=); -le(<=);-eq(==); -ne(!=)
能夠使用 && || 結合多個條件
if [ $a -gt 5 ] && [ $a -lt 10 ]; then
if [ $b -gt 5 ] || [ $b -lt 3 ]; then
用 (( )) 括起來 就能夠使用判斷符號了 如 if (( $a>1 ))
-a 與
-o 或
! 非
20.6 文件目錄屬性判斷
[ -f file ]判斷是不是普通文件,且存在 / [ ! -f file ]判斷是否不是普通文件,且不存在
[ -d file ] 判斷是不是目錄,且存在
[ -e file ] 判斷文件或目錄是否存在
[ -r file ] 判斷文件是否可讀
[ -w file ] 判斷文件是否可寫
[ -x file ] 判斷文件是否可執行
If [ $a == $b ] 若是string1等於string2 字符串容許使用賦值號作等號
if [ $string1 != $string2 ] 若是string1不等於string2
if [ -n $string ] 若是string 非空(非0),返回0(true)
if [ -z $string ] 若是string 爲空
if [ $sting ] 若是string 非空,返回0 (和-n相似)
20.7 if特殊用法
if [ -z "$a" ] 這個表示當變量a的值爲空時會怎麼樣
if [ -n "$a" ] 表示當變量a的值不爲空
if grep -q '123' 1.txt; then 表示若是1.txt中含有'123'的行時會怎麼樣
if [ ! -e file ]; then 表示文件不存在時會怎麼樣
if (($a<1)); then …等同於 if [ $a -lt 1 ]; then…
[ ] 中不能使用<,>,==,!=,>=,<=這樣的符號
20.8/20.9 case判斷
格式 case 變量名 in
value1)
command
;;
value2)
command
;;
*)
commond
;;
esac
在case程序中,能夠在條件中使用|,表示或的意思, 好比
2|3)
command
;;