標籤:
一、基本判斷條件
1)邏輯運算子
-a expr1 -a expr2 邏輯與
-o expr1 -o expr2 邏輯或
! !expr1 邏輯非
2)數值判斷
-eq num1 -eq num2 是否相等
-ne num1 -ne num2 是否不相等
-gt num1 -gt num2 是否大於
-ge num1 -ge num2 是否大於等於
-lt num1 -lt num2 是否小於
-le num1 -le num2 是否小於等於
3)字串判斷
= str1 = str2 字串是否相等
!= str1 != str2 字串是否不等
=~ str1 =~ str2 str1包含str2,注意整個條件放在"[[]]"之間
-n -n str1 字串長度是否不等於0
-z -z str2 字串長度是否等於0
4)檔案判斷
-r -r filename 檔案是否存在且可讀
-w -w filename 檔案是否存在且可寫
-s -s filename 檔案是否存在且長度非0
-f -f filename 檔案是否存在且是普通檔案
-d -d filename 檔案是否存在且是一個目錄
二、if判斷語句基本格式:
1)if判斷語句基本格式1:
if [ 判斷條件 ]
then
commands
else
fi
舉例:
#數值判斷:
read -p "enter a number(0/1): " num
if [ $num -eq 1 ]
then
echo "true"
else
echo "false"
fi
#字串判斷:
str1="this is a string"
if [[ "$str1" =~ "this" ]]
then
echo "true"
else
echo "false"
fi
#檔案判斷:
if [ -f ./test1.sh ]
then
echo "true"
else
echo "false"
fi
2)if判斷語句基本格式2:
if [ 判斷條件 ]; then
commands
elif [ 判斷條件 ]; then
commands
…
else
commands
fi
#舉例:
read -p "enter the score: " score
if [ "$score" -lt 0 ]; then
echo "enter a score in 0~100"
elif [ "$score" -gt 100 ]; then
echo "enter a score in 0~100"
elif [ "$score" -lt 60 ]; then
echo "fail score"
elif [ "$score" -lt 70 ]; then
echo "pass score"
elif [ "$score" -lt 80 ]; then
echo "fair score"
elif [ "$score" -lt 90 ]; then
echo "good score"
else
echo "excellent score"
fi
#注意:
1、 if與[]之間必須有空格
2、判斷條件前後必須有空格
3、then如果和if在同一行要用;分開
4、判斷條件含有變數,要用雙引號引起來
三、while迴圈語句基本格式
1)while迴圈語句基本格式:
#while [ 判斷條件 ]
min=1
max=10
while [ $min -le $max ]
do
echo $min
min=`expr $min + 1`
done
#注意:
1、while與[]之間必須要有空格
2、判斷條件前後要有空格
# while((判斷條件))
i=1
while(($i<=12))
do
if(($i%4==0))
then
echo $i
fi
i=$(($i+1))
done
#注意:
1、此種形式的內部結構類似c語言
2、注意賦值計算:i=$(($i+1))
四、for迴圈語句基本格式
1)for迴圈語句基本格式:
#數欄位形式
for i in {1..10}
do
echo $i
done
#詳細列出(項數不多)
for i in ‘a‘ ‘b‘ ‘c‘ ‘d‘
do
echo $i
done
#seq形式 起始從1開始
for i in `seq 10`
do
echo $i
done
#文法迴圈--有點像C文法
for ((i=1; i<+10; i++));
do
echo $i
done
#對存在的檔案進行迴圈
for shname in `ls *.sh`
do
echo "$shname" | awk -F. ‘{print $1}‘
done
linux之shell之if、while、for語句介紹