第一節(jié):if判斷
1.單分支
if [ 條件 ]
then
結(jié)果
fi
2.雙分支
if [ 條件1 ]
then
結(jié)果1
else
結(jié)果2
fi
3.多分支
if [ 條件1 ]
then
結(jié)果1
elif [ 條件2 ]
then
結(jié)果2
elif [ 條件3 ]
then
結(jié)果3
elif [ 條件4 ]
then
結(jié)果4
elif [ 條件5 ]
then
結(jié)果5
else
結(jié)果6
fi
4.if嵌套
if [ 條件1 ]
then
if [ 條件2 ] #再滿足條件1之后再判斷條件2
then
結(jié)果2
else
結(jié)果3
fi
else
結(jié)果4
fi
5.if判斷語句案例
案例: 輸入兩個數(shù)字 是否為整數(shù) 使用if方式
#!/bin/bash
read -p "請輸入第一個數(shù)字:" num1
read -p "請輸入第二個數(shù)字:" num2
if [ -z $num1 ]
then
echo "您輸入的第一個數(shù)字為空"&& exit
elif [ -z $num2 ]
then
echo "您輸入的第二個數(shù)字為空"&& exit
elif [[ "$num1" =~ ^[0-9]+$ && "$num2" =~ ^[0-9]+$ ]]
then
if [ $num1 -lt $num2 ]
then
echo "$num1<$num2"
elif [ $num1 -gt $num2 ]
then
echo "$num1>$num2"
else
echo "$num1=$num2"
fi
else
echo "您輸入了錯誤的值脸秽!"&& exit
fi
第二節(jié):for循環(huán)
1.for語句格式
for 變量名 in [取值列表]
do
循環(huán)體
done
[root@m01 /scripts]# cat 02for.sh
#!/bin/bash
IFS=' :.' #for循環(huán)默認(rèn)以空格為分隔符,來讀取數(shù)據(jù)祥国,這里指定 :. 為分隔符
for i in $(cat /etc/hosts);do
echo $i
done
2.for嵌套循環(huán)
for 變量名 in [取值列表]
do
for 變量名 in [取值列表]
do
循環(huán)體
done
done
第三節(jié):while循環(huán)
1.用法一:while后面接條件語句
while [ 條件表達(dá)式 ]
do
循環(huán)體
done
2.用法二:while按行讀取文件內(nèi)容
while read line
do
循環(huán)體
done<文件名
第四節(jié):流程控制語句
1.exit 退出整個腳本 不會繼續(xù)執(zhí)行
2.break 跳出本次循環(huán) 繼續(xù)往下執(zhí)行 跳出循環(huán)體
3.continue 結(jié)束當(dāng)前此次的命令,繼續(xù)下一次循環(huán)
4.continue 2 結(jié)束當(dāng)前此次的命令虑凛,繼續(xù)循環(huán)體下面的命令
第五節(jié):case 流程控制語句
case 變量名4 in
模式匹配1)
命令的集合
;;
模式匹配2)
命令的集合
;;
模式匹配3)
命令的集合
;;
*) *的下一行不需要有;;
echo USAGE[$0 1|2|3]
esac
第六節(jié):函數(shù)
1.函數(shù)定義的三種方式
test1(){
echo "第一種函數(shù)定義方式"
}
function test2(){
echo "第二種函數(shù)定義方式"
}
function test3 {
echo "第三種函數(shù)定義方式"
}
第七節(jié):數(shù)組
1.普通數(shù)組 只能以數(shù)字作為索引(下標(biāo))
第一種定義方式
數(shù)組名[索引]=值
[root@web scripts]# array[0]=shell
[root@web scripts]# array[1]=Linux
[root@web scripts]# array[2]=MySQL
第二種定義方式 一次定義多個值
數(shù)組名=(值)
[root@web02 ~]# array=(shell mysql [20]=kvm [50]=test)
declare -a #查看普通數(shù)組
1.select定義一個菜單
#!/bin/bash
main=(
nginx
tomcat
php
)
select i in ${main[*]}
do
echo $i
done
2.關(guān)聯(lián)數(shù)組 可以使用數(shù)字也可以使用字符串作為索引(下標(biāo))
declare -A array #關(guān)聯(lián)數(shù)組需要先定義再使用
[root@web02 ~]# array[index1]=Shell
[root@web02 ~]# array[index2]=Linux
[root@web02 ~]# array[index3]=MySQL
3.遍歷數(shù)組
查看數(shù)組的索引赁酝,值谣膳,和索引個數(shù)
1. echo ${array[*]} #遍歷數(shù)組的值
2. echo ${!array[*]} #遍歷索引
3. echo ${#array[*]} #查看索引個數(shù)