記錄:433
場景:Shell腳本while循環(huán)語句應(yīng)用。Shell腳本while循環(huán)語句應(yīng)用。while do done、while : do done、while true do done。
版本:CentOS Linux release 7.9.2009。
1.while常用格式
1.1格式一:while do done
while condition
do
command
done
1.2格式二:無限循環(huán)(while : do done)
while :
do
command
done
1.3格式三:無限循環(huán)(while true do done)
while true
do
command
done
2.使用while遍歷數(shù)組(while do done)
2.1腳本
腳本名稱:b2023052801.sh
腳本內(nèi)容:
#!/bin/bash
#1.定義數(shù)組
cityArray=("上海" "蘇州" "杭州" "寧波")
#2.獲取數(shù)組長度
lenth=${#cityArray[@]}
#3.使用while循環(huán)遍歷數(shù)組
index=0
while ((index < lenth))
do
echo "第$((index+1))個城市名稱: ${cityArray[index]}"
((index++))
done
2.2執(zhí)行與輸出
執(zhí)行命令:bash b2023052801.sh
執(zhí)行結(jié)果:
[root@hadoop211 tutorial]# bash b2023052801.sh
第1個城市名稱: 上海
第2個城市名稱: 蘇州
第3個城市名稱: 杭州
第4個城市名稱: 寧波
3.使用while無限循環(huán)(while : do done)
3.1腳本
腳本名稱:b2023052802.sh
腳本內(nèi)容:
#!/bin/bash
#1.定義數(shù)組
cityArray=("上海" "蘇州" "杭州" "寧波")
#2.獲取數(shù)組長度
lenth=${#cityArray[@]}
#3.使用while循環(huán)遍歷數(shù)組(使用字符串判斷,=號兩端需要空格)
index=0
while :
do
if [[ "${cityArray[index]}" = "杭州" ]];then
echo "第$((index+1))個城市名稱: ${cityArray[index]}"
break;
fi
((index++))
done
3.2執(zhí)行與輸出
執(zhí)行命令:bash b2023052802.sh
執(zhí)行結(jié)果:
[root@hadoop211 tutorial]# bash b2023052802.sh
第3個城市名稱: 杭州
4.使用while無限循環(huán)(while true do done)
4.1腳本
腳本名稱:b2023052803.sh
腳本內(nèi)容:
#!/bin/bash
#1.定義數(shù)組
cityArray=("上海" "蘇州" "杭州" "寧波")
#2.獲取數(shù)組長度
lenth=${#cityArray[@]}
#3.使用while循環(huán)遍歷數(shù)組(使用字符串判斷,=號兩端需要空格)
index=0
while true
do
if [[ "${cityArray[index]}" = "蘇州" ]];then
echo "第$((index+1))個城市名稱: ${cityArray[index]}"
break;
fi
((index++))
done
4.2執(zhí)行與輸出
執(zhí)行命令:bash b2023052803.sh
[root@hadoop211 tutorial]# bash b2023052803.sh
第2個城市名稱: 蘇州
5.使用while循環(huán)(while read do done)
5.1腳本
腳本名稱:b2023052804.sh
腳本內(nèi)容:
#!/bin/bash
echo -n '請輸入長三角直轄市名稱: '
while read city
do
#注意if和[[]]之間需要空格
if [[ $city = "上海" || $city = "Shanghai" ]];then
echo "${city}是長三角直轄市."
break;
else
echo "${city}不是長三角直轄市."
echo -n '請輸入長三角直轄市名稱: '
fi
done
5.2執(zhí)行與輸出
執(zhí)行命令:bash b2023052804.sh
執(zhí)行結(jié)果:
[root@hadoop211 tutorial]# bash b2023052804.sh
請輸入長三角直轄市名稱: 蘇州
蘇州不是長三角直轄市.
請輸入長三角直轄市名稱: 上海
上海是長三角直轄市.
6.使用while循環(huán)(while read do done < )
6.1腳本
腳本名稱:b2023052805.sh
腳本內(nèi)容:
#!/bin/bash
echo '從文件中讀取內(nèi)容'
filePath=`pwd`
while read line
do
echo ${line}
done <${filePath}/province.txt
6.2執(zhí)行與輸出
執(zhí)行命令:bash b2023052805.sh
執(zhí)行結(jié)果:
[root@hadoop211 tutorial]# bash b2023052805.sh
從文件中讀取內(nèi)容
長三角省份有浙江、江蘇等。
長三角最大都市是上海。
長三角經(jīng)濟發(fā)達。
以上,感謝。文章來源:http://www.zghlxwxcb.cn/news/detail-463134.html
2023年5月28日文章來源地址http://www.zghlxwxcb.cn/news/detail-463134.html
到了這里,關(guān)于Shell腳本while循環(huán)語句應(yīng)用的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!