Shell腳本之條件語句

Shell腳本之條件語句

Shell腳本之條件語句

本章結構

條件測試
文件測試
整數測試
字符串與邏輯測試
if語句
if單分支語句
if雙分支語句
if多分支語句
if嵌套語句

一.條件測試

Shell腳本之條件語句

格式1: test  條件表達式

格式2:[ 條件表達式 ]   

二.文件測試

Shell腳本之條件語句

-d:測試是否爲目錄(Directory)
-e:測試目錄或文件是否存在(Exist)
-f:測試是否爲文件(File)
-r:測試當前用戶是否有權限讀取(Read)
-w:測試當前用戶是否有權限寫入(Write)
-x:測試當前用戶是否有權限執行(eXcute)
[root@localhost ~]# test -d /etc/yum  //測試/etc/yum是否是目錄
[root@localhost ~]# echo $?         //上一條命令執行狀態0就是正常執行,1就是錯誤
0
[root@localhost ~]# test -f /etc/yum   //測試/etc/yum是否是文件
[root@localhost ~]# echo $?
1
[root@localhost ~]# test -e /etc/yum  //測試/etc/yum是否存在
[root@localhost ~]# echo $?
0
[root@localhost ~]# 

三.整數測試

Shell腳本之條件語句

-eq:等於(Equal)
-ne:不等於(Not Equal)
-gt:大於(Greater Than)
-lt:小於(Lesser Than)
-le:小於或等於(Lesser or Equal)
-ge:大於或等於(Greater or Equal)

[root@localhost ~]# [ $(who|wc -l) -gt 10 ]&& echo "有點多!" //統計當前用戶量
有點多!

四.字符串比較

Shell腳本之條件語句

=:字符串內容相同
!=:字符串內容不同,!表示相反的意思
-z:字符串內容爲空

五.邏輯測試

Shell腳本之條件語句

-a或&&:邏輯與、“而且”的意思
-o或||: 邏輯或、“或者”的意思
!:邏輯否

[root@localhost ~]# [ ! -e /opt/abc ]&&mkdir /opt/abc  // /opt/abc這個目錄不存在我就創建這個目錄
[root@localhost ~]# ls /opt
abc  rh

6.if語句單分支

Shell腳本之條件語句

#!/bin/bash
mulu="/etc/ccc"  
if [ ! -d $mulu ] 
then
        mkdir -p $mulu
fi

7.if雙分支語句

Shell腳本之條件語句

#!/bin/bash

ping -c 3 -i 0.2 -W 3 $1 &>/dev/null
if [ $? -eq 0 ]
then
        echo "Host $1 is up "
else
        echo "Host $1 is down "
fi
-C發數據包  ,-0.2每隔兩秒發一次  -W 3次回覆  所有輸出到這個無用的目錄中

[root@localhost ~]# ./c.sh
Host  is down 

8.if多分支和嵌套語句

Shell腳本之條件語句

#!/bin/bash
#一場跑步比賽,10秒內進入決賽,進入決賽之後會被分進男子組或女子組
read -p "請輸入你的比賽時間" soucre
if [ $soucre -lt 10 ]
 then
 echo "進入決賽"
 read -p "請輸入你的性別(男/女) " sex
 if [ $sex = "男" ]
   then
   echo "進入男子組"
 else
   echo "進入女子組"
 fi
else "被淘汰"
fi
~                                                                                        
~                            
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章