20.5 Shell腳本中的邏輯判斷
格式1:if 條件 ; then 語句; fi
1. 建立if1.sh測試腳本:
[root@hao-01 ~]# vi if1.sh
a=5,如果a大于3,滿足這個條件,顯示ok
添加内容:
#!/bin/bash
a=5
if [ $a -gt 3 ]
then
echo ok
fi
2. 執行if1.sh腳本:
[root@hao-01 ~]# sh if1.sh
格式2:if 條件; then 語句; else 語句; fi
1. 建立if2.sh測試腳本:
[root@hao-01 ~]# vi if2.sh
a=1,如果a大于3,滿足這個條件,顯示ok; 不滿足這個條件,顯示nook
a=1
else
echo noook
2. 執行if2.sh腳本:
[root@hao-01 ~]# sh if2.sh
檢視執行過程:
[root@hao-01 ~]# sh -x if2.sh
格式3:if …; then … ;elif …; then …; else …; fi
1. 建立if3.sh測試腳本:
a=3,如果a大于4,(不滿足繼續判斷)a大于6; 滿足小于6并且大于1,顯示nook
a=3
if [ $a -gt 4 ]
echo ">"
elif [ $a -gt 6 ]
echo "<6 && >1"
echo nook
2. 執行if3.sh腳本:
[root@hao-01 ~]# sh if3.sh
[root@hao-01 ~]# sh -x if3.sh
邏輯判斷表達式:
-gt(>) -lt(<) -eq(==) -ne(!=) -ge(>=) -le(<=)
-gt大于 -lt小于 -eq等于 -ne不等于 -ge大于等于 -le小于等于
例:if [ $a -gt $b ] if [ $a -lt 5 ] if [ $b -eq 10 ]
可以使用 &&并且 ||或者 多個判斷條件
例: if [ $a -gt 5 ] && [ $a -lt 10 ]; then
if [ $b -gt 5 ] || [ $b -lt 3 ]; then
20.6 檔案目錄屬性判斷
[ -f file ]判斷是否是普通檔案,且存在
1. 建立file1.sh測試腳本:
[root@hao-01 ~]# vi file1.sh
判斷/tmp/hao.txt是不是普通檔案?是否存在?如果不存在,建立這個檔案!
f="/tmp/hao.txt"
if [ -f $f ]
echo $f exist
touch $f
2. 執行file1.sh腳本(檔案不存在的情況下):
[root@hao-01 ~]# sh -x file1.sh
執行filel.sh腳本(檔案存在的情況下):
[ -d file ] 判斷是否是目錄,且存在
1. 建立file2.sh測試腳本:
[root@hao-01 ~]# vi file2.sh
判斷/tmp/hao.txt是不是目錄?是否存在?如果不是目錄,也不存在這樣的目錄,建立這個目錄!
if [ -d $f ]
2. 執行file2.sh腳本(檔案不存在的情況下):
[root@hao-01 ~]# sh -x file2.sh
[ -e file ] 判斷檔案或目錄是否存在
1. 建立file3.sh測試腳本:
[root@hao-01 ~]# vi file3.sh
判斷/tmp/hao.txt不管是目錄或檔案,隻要不存在的,就建立檔案或目錄!
if [ -e $f ]
2. 執行file3.sh腳本
[root@hao-01 ~]# sh -x file3.sh
[ -r file ] 判斷檔案是否可讀
1. 建立file4.sh測試腳本:
判斷/tmp/hao.txt檔案是否可讀?
[root@hao-01 ~]# vim file4.sh
if [ -r $f ]
echo $f readable
2. 執行file4.sh腳本
[root@hao-01 ~]# sh -x file4.sh
[ -w file ] 判斷檔案是否可寫
1. 建立file5.sh測試腳本:
判斷/tmp/hao.txt檔案是否可寫?
[root@hao-01 ~]# vim file5.sh
if [ -w $f ]
echo $f writeable
2. 執行file5.sh腳本
[root@hao-01 ~]# sh -x file5.sh
[ -x file ] 判斷檔案是否可執行
判斷/tmp/hao.txt檔案是否可執行?
[root@hao-01 ~]# vim file6.sh
if [ -x $f ]
echo $f exeable
2. 執行file56.sh腳本(沒有輸出就是不可執行!可是腳本配置也是權限)
[root@hao-01 ~]# sh -x file6.sh
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 cace判斷(上)
#!/bin/bash
read -p "Please input a number: " n
if [ -z "$n" ]
echo "Please input a number."
exit 1
n1=`echo $n|sed 's/[0-9]//g'`
if [ -n "$n1" ]
echo "Please input a number."
exit 1
if [ $n -lt 60 ] && [ $n -ge 0 ]
tag=1
elif [ $n -ge 60 ] && [ $n -lt 80 ]
tag=2
elif [ $n -ge 80 ] && [ $n -lt 90 ]
tag=3
elif [ $n -ge 90 ] && [ $n -le 100 ]
tag=4
else
tag=0