在linux shell程式設計中,if、for、while、case等條件流程控制語句用的非常多,把這些學好,對提公升指令碼的功力有非常大的幫助。下面將逐個來講解具體的用法:
if (表示式) #if ( variable in array )案例一,測試數字大小語句1else
語句2fi
#!/bin/sh
num=100
if (( $num > 4 )) ;then
echo 「this num is $num greater 4 !」
fi
案例二,測試目錄是否存在,不存在則新建(注意,中括號之間必須要空格)
#!/bin/sh
#judge dir exist
if [ ! -d /data/20140515 ];then
mkdir -p /data/20140515
else
echo 「this dir is exist,please exit …..」
fi
邏輯運算子解析:
-f案例三,多個條件測試判斷判斷檔案是否存在 eg: if [ -f filename ]
-d判斷目錄是否存在 eg: if [ -d dir ]
-eq等於 應用於:整型比較
-ne不等於 應用於:整型比較
-lt小於 應用於:整型比較
-gt大於 應用於:整型比較
-le小於或等於 應用於:整型比較
-ge大於或等於 應用於:整型比較
-a雙方都成立(and) 邏輯表示式 –a 邏輯表示式
-o單方成立(or) 邏輯表示式 –o 邏輯表示式
-z空字串
#!/bin/sh
scores=80;
if [[ $scores -gt 85 ]]; then
echo "very good!";
elif [[ $scores -gt 75 ]]; then
echo "good!";
elif [[ $scores -gt 60 ]]; then
echo "pass!";
else
echo "no pass!";
fi;
for 變數 in 字串案例一,列印seq多個數do語句1
done
#!/bin/sh
for i in `seq 15`
do echo 「num is $i」
done
案例二,找到相關log,然後批量打包
#!/bin/sh
for i in `find /var/log -name 「*.log」`
do tar –czf 2014log.tgz $i
done
while 條件語句案例一,while條件判斷數字do語句1
done
#!/bin/sh
i=1;
while [[ $i -lt 10 ]];do
echo $i;
((i++));
done;
案例二,while逐行讀取某個檔案
#!/bin/sh
while read line
do echo $line;
done < /etc/hosts
until 條件直到滿足條件,才退出。否則執行action。doaction
done
案例一,條件判斷數字
#!/bin/sh
a=10;
until [[ $a -lt 0 ]];do
echo $a;
((a--));
done;
case $arg in案例一,建立選擇引數指令碼pattern1)
語句1;;
pattern2)
語句2;;
*)語句3
;;
esac
#!/bin/sh
case $1 in
monitor_log)
monitor_log
;;archive_log)
archive_log
;;* )
echo "usage:"
;;esac
#!/bin/sh
ps3="what you like most of the open source system?"
select i in centos redhat ubuntu
do echo "your select system: "$i
done
shell流程控制語句
任何程式語言都離不開流程控制語句,其實程式設計基本上就是掌握了流程控制語句,然後加上函式 或者是方法 以及變數基本就差不多了,語法的東西很少,主要還是處理邏輯。所以,邏輯思維很重要。對於計算機來說,它只知道有或者沒有,是正或者是負,有電或者沒電,其實就是1和0的事兒。因此,if語句很重要,但又很簡單...
Shell基礎 流程控制語句
0 表示當前指令碼檔案的名稱 獲取當前指令碼有多少個引數 對應所有引數的值 n 對應第n個引數的值 表示當前指令碼執行結果 0表示成功,非0表示失敗 有兩種方式 a.test 命令 b.w test.sh 引數 檔名 2.1 檔案測試 2.2 邏輯測試 與 或 非 2.3 整數值比較測試 2.4 字...
shell 之 流程控制語句if
if 條件 then commands fi bin bash ifls shell then echo there is a dir named shell fi執行結果 注 根據我們命令退出的碼來進行判斷 是否為 0 如果是0,那麼就會執行then後面的命令 if 條件 then command...