第二章shell腳本(二)
Test文件測試的常見選項有
-d:測試是否爲目錄(directory)
-e:測試目錄或文件是否存在(exist)
-f:測試是否爲文件(file)
-r:測試當前用戶是否有權限讀取(read)
-w:測試當前用戶是否有寫入權限(write)
-x:測試是否設置有可執行權限(excute)
Test常用表達示有兩種
test 表達示 [表達示]
常用的表達示爲後者因爲更加貼近編程習慣,如下
[root@localhost ~]# [ -d /media/Server/ ] ; echo $? #配合$?查看,返回值爲非0說明沒有這個目錄
1
[root@localhost ~]# ld /media/Server/ #驗證
ld: /media/Server/: No such file: No suchfile or directory
整數值比較包含的選項
-eq:等於(equal)
-ne:不等於(not equal)
-lt:小於(lesser than)
-gt:大於(greater than)
-le:小於等於(lesser or equal)
-ge:大於等於(greater or equal)
整數值比較在腳本中應用較多,如判斷已登錄用戶數量。
[root@localhost shelltest]# stati=`who | wc-l`
[root@localhost shelltest]# [ $stati -le 5 ]&& echo "Active users less than 5 peopl"
Active users less than 5 peopl
字符串比較
=:第一個字符串與第2個字符串相同
!=:第1個字符串與第2個字符串不相同,“!”爲取反的意思
-z:檢查字符是否爲空。
邏輯測試
&&:邏輯與,表示“而且”的意思,當兩個條件都成立時纔會返回值爲0,使用test測試時“&&”可以改爲“-a”
||:邏輯或,表示“或者”的意思,只要前後有一個條件成立,整個測試命令的返回值即爲0,Test時可改爲“-o”
!:邏輯否,表示“不”的意思,只有當指定條件不成立時,整個測試命令的返回值即爲0。
用&&做例子:
[root@localhost ~]# [ 6 -ne 4 ] &&echo "yes"
Yes
If 語句
if語句的選擇結構分爲三種基本類型
if單分支結構,格式如下
if 條件測試操作
then
命令序列
fi
單分支案例
[root@localhost ~]# vim test.sh
#!/bin/bash
#########if單分支案例############
who=`who |wc -l`
if [ $who -le 5 ];then
echo "Active users less than 5people"
fi
[root@localhost ~]# sh test.sh
Active users greater than 5 people
雙分支If語句
雙分支if語句要求針對“條件成立”和“條件不成立”兩種情況執行兩種不同的操作
[root@localhost ~]# vim test.sh
#!/bin/bash
#########if多分支案例############
who=`who |wc -l`
if [ $who -le 5 ];then
echo "Active users less than 5people"
else
echo "Active users greater than people"
fi
[root@localhost~]# sh test.sh
Activeusers greater than 5 people
多分支if語句
多分支if語句根據測試結果,執行不同的操作,所以能夠嵌套使用,進行多次判斷。格式如下:
if單分支結構,格式如下
if 條件測試操作1
then
命令序列1
elif 條件測試操作2
then
命令序列2
Else
命令序列3
fi
多分支案例:
[root@localhost ~]# vim Scores_query.sh
#!/bin/bash
###########分數優、良、差查詢腳本###########
read -p " 請輸入您的分數(1-100):" score
if [ $score -ge 85 ] && [ $score -le100 ]
then
elif [ $score -ge 70 ] && [ $score -le84 ]
then
echo " 您的分數爲$score,良"
elif [ $score -ge 60 ] && [ $score-le 69 ]
then
echo " 您的分數爲$score分, 爲及格"
elif [ $score -le 59 ]
then
echo " 您的分數爲$score分, 爲不及格"
else
echo " 請輸入1-100之間的分數"
fi
[root@localhost ~]# sh Scores_query.sh
請輸入您的分數(1-100):100
您的分數爲100分, 爲優秀
[root@localhost ~]# sh Scores_query.sh
請輸入您的分數(1-100):80
您的分數爲80分, 爲良