最近在看《鳥哥的LINUX私房菜 基礎(chǔ)學(xué)習(xí)篇》彬呻,目前看到了shell腳本這一章绍傲,打算在這里簡(jiǎn)單記錄一下這一整章的學(xué)習(xí)過程和相關(guān)的知識(shí)點(diǎn)说莫。
參考資料:《鳥哥的LINUX私房菜 基礎(chǔ)學(xué)習(xí)篇》第四版 第十二章
實(shí)驗(yàn)環(huán)境: Ubuntu18.04
在上一節(jié)中,我們學(xué)習(xí)了如何在shell腳本中使用條件判斷嗜历,根據(jù)判斷的結(jié)果分別執(zhí)行不同的程序段赊时。本節(jié),我們將學(xué)習(xí)如何在shell腳本中利用循環(huán)行拢。
循環(huán)也是編程中很重要的內(nèi)容祖秒,通過循環(huán)可以讓程序自動(dòng)的、多次執(zhí)行某一程序段舟奠。在shell腳本中主要使用的有三種循環(huán)竭缝,下面一一進(jìn)行介紹。
1. 不定循環(huán)
最常見的不定循環(huán)有兩種:while do done和until do done沼瘫。
#while do done 當(dāng)條件成立時(shí)抬纸,就進(jìn)行循環(huán),直到條件不成立時(shí)停止
while [ condition ]
do
程序段落
done
#until do done 當(dāng)條件成立時(shí)耿戚,終止循環(huán)湿故,否則進(jìn)行循環(huán)
until [ condition ]
do
程序段落
done
-
簡(jiǎn)單的示例
下面分別用while和until編寫了同一個(gè)功能的小腳本阿趁,來對(duì)比它們的不同
#文件名:yes_to_stop.sh
#!/bin/bash
# Program:
# Repeat question until user input correct answer.
# History:
# 2019/2/25 LaiFeng
while [ "$yn" != "yes" -a "$yn" != "YES" ] #當(dāng)用戶輸入不是'yes'且'YES'時(shí),執(zhí)行程序段
do
read -p "Please input yes/YES to stop this program:" yn
done
echo "OK, you input the correct answer."
#文件名:yes_to_stop-2.sh
#!/bin/bash
# Program:
# Repeat question until user input correct answer.
# History:
# 2019/2/25 LaiFeng
until [ "$yn" == "yes" -o "$yn" == "YES" ] #當(dāng)用戶輸入是'yes'或者'YES'時(shí)坛猪,停止
do
read -p "Please input yes/YES to stop this program:" yn
done
echo "OK, you input the correct answer."
2.固定循環(huán) for...do...done
for...do...done的語法:
for var in con1 con2 con3
do
程序段
done
從它語法中可以看出脖阵,固定循環(huán)其實(shí)就是將已知的幾個(gè)值(con1 con2 con3)分別代入(var),執(zhí)行程序段墅茉。
- 簡(jiǎn)單的示例
#文件名:show_animal.sh
#!/bin/bash
# Program:
# Using for...loop to print 3 animals
# History:
# 2019/2/25 LaiFeng
for animal in dog cat elephant
do
echo "There are ${animal}s..."
done
再看一個(gè)更有趣的示例命黔。在這個(gè)示例中,讓用戶輸入某個(gè)目錄名就斤,然后程序列出該目錄下所有文件的權(quán)限悍募。
#文件名:dir_perm.sh
#!/bin/bash
# Program:
# User input dir name, I will find the permission of files.
# History:
# 2019/2/25 LaiFeng
read -p "Please input a directory:" dir
#判斷目錄是否存在
if [ "$dir" == "" -o ! -d "$dir" ]; then
echo "The $dir is NOT exist in your system."
exit 1
fi
#列出目錄下所有文件名
filelist=$(ls $dir)
for filename in ${filelist} #遍歷所有文件名
do
perm=""
test -r "${dir}/${filename}" && perm="$perm readable"
test -w "${dir}/${filename}" && perm="$perm writable"
test -x "${dir}/${filename}" && perm="$perm executable"
echo "Thie file ${dir}/${filename}'s permission is ${perm}"
done
3. for...do...done 的數(shù)值處理
for...do...done還有另一種用法。這種用法與其他編程語言中的用法基本一致洋机。它的語法如下:
for ((初始值坠宴;終止條件;賦值運(yùn)算)) #注意槐秧,需要兩個(gè)括號(hào)
do
程序段
done
- 簡(jiǎn)單的示例
#文件名:cal_1_n.sh
#!/bin/bash
# Program:
# Use loop to calculate "1+2+...+n"
# History:
# 2019/2/25 LaiFeng
read -p "Please input a number, I will count for 1+2+...+n: " num
s=0
for ((i=1;i<=$num;i=i+1))
do
s=$(($s+$i)) #shell腳本數(shù)值計(jì)算:$((計(jì)算式))
done
echo "The result of '1+2+3...+$num' is ==> $s"
以上就是關(guān)于shell腳本中循環(huán)的簡(jiǎn)單介紹啄踊。想要了解更多關(guān)于shell腳本的知識(shí)?歡迎參考Linux shell腳本 :)