shell腳本及常用循環語句有哪些,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
Shell字面理解就是個“殼”,是操作系統(內核)與用戶之間的橋梁,充當命令解釋器的作用,將用戶輸入的命令翻譯給系統執行。Linux中的shell與Windows下的DOS一樣,提供一些內建命令(shell命令)供用戶使用,可以用這些命令編寫shell腳本來完成復雜重復性的工作
什么是腳本?
腳本就是由Shell命令組成的件,這些命令都是可執行程序的名字,腳本不用編譯即可運行。它通過解釋器解釋運行,所以速度相對來說比較慢。
shell腳本的優點
1.自動化管理的重要依據
2.追蹤與管理系統的重要工
3.簡單偵測功能
4.連續指令單一化
5.簡易的數據處理
6.跨平臺支持與學習歷程較短
編寫shell腳本注意事項
指令的執行是從上而下、從左而右的分析與執行;
指令的下達就如同之前提到的:指令、選項與參數間的多個空白都會被忽略掉;
空白行也將被忽略掉,并且 [tab] 按鍵所推開的空白同樣視為空白鍵;
如果讀取到一個 Enter 符號(CR),就嘗試開始執行該行(或該串)命令;
至于如果一行的內容太多,則可以使用“ [Enter] ”來延伸至下一行;
“ # ”可做為注解!任何加在 # 后面的數據將全部被視為注解字而被忽略!
執行shell腳本分為四點
直接指令下達: shell.sh 件必須要具備可讀與可執行(nx) 的權限,然后:
絕對路徑:使用/home/dtsai/shell.sh 來下達指令;
相對路徑:假設工作目錄在/home/dmtsai/,則使用.shel.sh 來執行
*變量"PATH"功能:將shell.sh放在PATH指定的目錄內,例如: ~/bin/
以bash程序來執行:通過“bash shell,sh”或“sh shell.sh "來執行
[root@localhost ~]# vim a.sh #!/bin/bash echo -e "hellow \a \n" exit 0 [root@localhost ~]# chmod a+x a.sh [root@localhost ~]# sh a.sh hellow
第一行 #!/bin/bash 在宣告這個 script 使用的 shell 名稱:
程序內容的說明:
主要環境變量的宣告:建議務必要將一些重要的環境變量設置好,我個人認為, PATH 與 LANG (如果有使用到輸出相關的信息時)是當中最重要的!如此一來,則可讓我們這支程序在進行時,可以直接下達一些外部指令,而不必寫絕對路徑呢!
主要程序部分就將主要的程序寫好即可
執行成果告知(定義回傳值)一個指令的執行成功與否,可以使用$?這個變量來觀察~那么我們也可以利用 exit 這個指令來讓程序中斷,并且回傳一個數值給系統
\a 發出警告聲;\n 換行且光標移至行首;
對談式腳本:變量內容由使用者決定量
隨日期變化:利用date進行件的創建
數值運算:簡單的加減乘除
對談式腳本:變量內容由使用者決定量
[root@localhost ~]# vim b.sh
#!/bin/bash
read -p "Please input your first name: " firstname
read -p "Please input your last name: " lastname
echo -e "\nYour full name is: ${firstname} ${lastname}"
[root@localhost ~]# sh b.sh
Please input your first name: x
Please input your last name: a
Your full name is: x a隨日期變化:利用date進行件的創建
[root@localhost ~]# vim x.sh
#!/bin/bash
echo -e "I will use 'touch' command to create 3 files."
read -p "Please input your filename: "
fileuserfilename=${fileuser:-"filename"}
date1=$(date --date='2 days ago' +%Y%m%d)
date2=$(date --date='1 days ago' +%Y%m%d)
date3=$(date +%Y%m%d)
file1=${filename}${date1}
file2=${filename}${date2}
file3=${filename}${date3}
touch "${file1}"
touch "${file2}"
touch "${file3}"
filename: a
[root@localhost ~]# ls \\可以看到創建了3天的件
20191203 20191205 a.sh initial-setup-ks.cfg 公共 視頻 檔 音樂
20191204 anaconda-ks.cfg b.sh x.sh 模板 圖片 下載 桌面數值運算:簡單的加減乘除
[root@localhost ~]# vim q.sh
#!/bin/bash
echo -e "You SHOULD input 2 numbers, I will multiplying them! \n"
read -p "first number: " firstnu
read -p "second number: " secnu
total=$((${firstnu}*${secnu}))
echo -e "\nThe result of ${firstnu} x ${secnu} is ==> ${total}"
[root@localhost ~]# sh q.sh
You SHOULD input 2 numbers, I will multiplying them!
first number: 2
second number: 3
The result of 2 x 3 is ==> 6利用test指令的測試功能




if條件測試語句
if條件測試語句可以讓腳本根據實際情況自動執行相應的命令。從技術角度來講,if語句分為單分支結構、雙分支結構、多分支結構;其復雜度隨著靈活度一起逐級上升。
1.if條件語句的單分支結構由if、then、fi關鍵詞組成,而且只在條件成立后才執行預設的命令,相當于口語的“如果……那么……”。單分支的if語句屬于最簡單的一種條件判斷結構。

案例:
[root@localhost ~]# vim x.sh
#!/bin/bash
read -p "Please input (Y/N): " yn
if [ "${yn}" == "Y" ] || [ "${yn}" == "y" ]; then
echo "OK, continue"
exit 0
fi
if [ "${yn}" == "N" ] || [ "${yn}" == "n" ]; then
echo "Oh, interrupt!"
exit 0
fi
echo "I don't know what your choice is" && exit 0
[root@localhost ~]# sh x.sh
Please input (Y/N): Y
OK, continue
[root@localhost ~]# sh x.sh
Please input (Y/N): N
Oh, interrupt!
[root@localhost ~]# sh x.sh
Please input (Y/N): asd
I don't know what your choice is2.if條件語句的雙分支結構由if、then、else、fi關鍵詞組成,它進行一次條件匹配判斷,如果與條件匹配,則去執行相應的預設命令;反之則去執行不匹配時的預設命令,相當于口語的“如果……那么……或者……那么……”。if條件語句的雙分支結構也是一種很簡單的判斷結構。
https://s1.51cto.com/images/blog/201809/17/e6093221273e0d416b0ee944c5e318c4.jpg?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
還用上面的案例:
[root@localhost ~]# vim x.sh
#!/bin/bash
read -p "Please input (Y/N): " yn
if [ "${yn}" == "Y" ] || [ "${yn}" == "y" ]; then
echo "OK, continue"
elif [ "${yn}" == "N" ] || [ "${yn}" == "n" ]; then
echo "Oh, interrupt!"
else
echo "I don't know what your choice is"
fi
[root@localhost ~]# sh x.sh
Please input (Y/N): Y
OK, continue3.if條件語句的多分支結構由if、then、else、elif、fi關鍵詞組成,它進行多次條件匹配判斷,這多次判斷中的任何一項在匹配成功后都會執行相應的預設命令,相當于口語的“如果……那么……如果……那么……”。if條件語句的多分支結構是工作中最常使用的一種條件判斷結構,盡管相對復雜但是更加靈活。

案例:
[root@localhost ~]# vim a.sh
#!/bin/bash
if [ "${1}" == "hello" ]; then
echo "Hello, how are you ?"
elif [ "${1}" == "" ]; then
echo "You MUST input parameters, ex> {${0} someword}"
else
echo "The only parameter is 'hello', ex> {${0} hello}"
fi
[root@localhost ~]# sh a.sh \\可以看到必須加參數才能執行
You MUST input parameters, ex> {a.sh someword}
[root@localhost ~]# sh a.sh hello
Hello, how are you ?利用if... then:網絡狀態
[root@localhost ~]# vim netstat.sh
#!/bin/bash
echo "Now, I will detect your Linux server's services!"
echo -e "The www, ftp, ssh, and mail(smtp) will be detect! \n"
testfile=/dev/shm/netstat_checking.txt
netstat -tuln > ${testfile}
testing=$(grep ":80 " ${testfile}) \\偵測80端口是否存在
if [ "${testing}" != "" ]; then
echo "WWW is running in your system."
fi
testing=$(grep ":22 " ${testfile}) \\偵測22端口是否存在
if [ "${testing}" != "" ]; then
echo "SSH is running in your system."
fi
testing=$(grep ":21 " ${testfile}) \\偵測21端口是否存在
if [ "${testing}" != "" ]; then
echo "FTP is running in your system."
fi
testing=$(grep ":25 " ${testfile})
if [ "${testing}" != "" ]; then
echo "Mail is running in your system."
fi
[root@localhost ~]# sh netstat.sh
Now, I will detect your Linux server's services!
The www, ftp, ssh, and mail(smtp) will be detect!
SSH is running in your system. \\看到ssh正在系統中運行
Mail is running in your system. \\郵件服務正在系統中運行for條件循環語句
for循環語句允許腳本一次性讀取多個信息,然后逐一對信息進行操作處理,當要處理的數據有范圍時,使用for循環語句再適合不過了。

for...do...done(固定循環)
案例:
假設我有三種動物,分別是 dog, cat, elephant 三種,我想每一行都輸出這樣:“There are dogs...”之類的字樣,則可以:
[root@localhost ~]# vim w.sh
for animal in dog cat elephant
do
echo "There are ${animal}s.... "
done
[root@localhost ~]# sh w.sh
There are dogs....
There are cats....
There are elephants....while條件循環語句
while條件循環語句是一種讓腳本根據某些條件來重復執行命令的語句,它的循環結構往往在執行前并不確定最終執行的次數,完全不同于for循環語句中有目標、有范圍的使用場景。while循環語句通過判斷條件測試的真假來決定是否繼續執行命令,若條件為真就繼續執行,為假就結束循環。

while... do...done,until...do...done(不定循環)
While:當滿足后面條件時才進行循環
Until:當不滿足后面條件時才進行循環
案例:
假設我要讓使用者輸入 yes 或者是 YES 才結束程序的執行,否則就一直進行告知使用者輸入字串。
[root@localhost ~]# vim s.sh
#!/bin/bash
while [ "${yn}" != "yes" -a "${yn}" != "YES" ]
do
read -p "Please input yes/YES to stop this program: " yn
done
echo "OK! you input the correct answer."
[root@localhost ~]# sh s.sh
Please input yes/YES to stop this program: asd
Please input yes/YES to stop this program: asd
Please input yes/YES to stop this program: YES
OK! you input the correct answer.case條件測試語句
case語句是在多個范圍內匹配數據,若匹配成功則執行相關命令并結束整個條件測試;而如果數據不在所列出的范圍內,則會去執行星號(*)中所定義的默認命令。

利用case .... esac判斷
[root@localhost ~]# vim aa.sh
#!/bin/bash
case ${1} in
"hello")
echo "Hello, how are you ?"
;;
"")
echo "You MUST input parameters, ex> {${0} someword}"
;;
*)
echo "Usage ${0} {hello}"
;;
esac
[root@localhost ~]# sh aa.sh
You MUST input parameters, ex> {aa.sh someword}
[root@localhost ~]# sh aa.sh hello
Hello, how are you ?一般來說,使用“ case $變量 in ”這個語法中,當中的那個“ $變量 ”大致有兩種取得的方式:
直接下達式:例如上面提到的,利用“ script.sh variable ” 的方式來直接給予 $1 這個變量的內容,這也是在 /etc/init.d 目錄下大多數程序的設計方式。
互動式:通過 read 這個指令來讓使用者輸入變量的內容。
讓使用者能夠輸入 one, two, three ,并且將使用者的變量顯示到屏幕上,如果不是 one, two, three 時,就告知使用者僅有這三種選擇。
[root@localhost ~]# vim bb.sh
#!/bin/bash
echo "This program will print your selection !"
#read -p "Input your choice: " choice
#case ${choice} in
case ${1} in
"one")
echo "Your choice is ONE"
;; "two") echo "Your choice is TWO" ;;
"three")
echo "Your choice is THREE"
;;
*)
echo "Usage ${0} {one|two|three}"
;;
esac
[root@localhost ~]# sh bb.sh
This program will print your selection !
Usage bb.sh {one|two|three}
[root@localhost ~]# sh bb.sh one
This program will print your selection !
Your choice is ONE
[root@localhost ~]# sh bb.sh two
This program will print your selection !
Your choice is TWO函數
函數的定義
在shell 中有兩種定義函數的語法格式,分別為:
函數名()
{
命令序列
}
或者:
function 函數名() /function 可以不寫
{
命令序列
}
函數定義好后,用戶可以在shell 中直接調用,調用時不用帶上()
調用語法 函數名 參數1 參數2 .... 函數中的變量 均為全局變量,沒有局部變量 函數的調用 可以傳遞參數,在函數中用$1,$2, $3...來引用傳遞的參數。
還用上面的案例:用函數調用實現
[root@localhost ~]# vim cc.sh
#!/bin/bash
function printit(){
echo -n "Your choice is "
}
echo "This program will print your selection !"
case ${1} in
"one")
printit; echo ${1} | tr 'a-z' 'A-Z' \\將參數的大小寫轉換
;; "two")
printit; echo ${1} | tr 'a-z' 'A-Z'
;;
"three")
printit; echo ${1} | tr 'a-z' 'A-Z'
;;
*)
echo "Usage ${0} {one|two|three}"
;;
esac
[root@localhost ~]# sh cc.sh
This program will print your selection !
Usage cc.sh {one|two|three}
[root@localhost ~]# sh cc.sh one
This program will print your selection !
Your choice is ONE
[root@localhost ~]# sh cc.sh two
This program will print your selection !
Your choice is TWOShell腳本的追蹤與debug
sh執行的選項與參數: -n :不要執行script(腳本),僅查詢語法的問題 -v :在執行script前,先將腳本的內容輸出到屏幕上 -x :將使用到的腳本內容顯示到屏幕上,
案例:
[root@localhost ~]# sh -n aa.sh \\不報錯證明正常
[root@localhost ~]# sh -v aa.sh \\輸出到屏幕上
#!/bin/bash
case ${1} in
"hello")
echo "Hello, how are you ?"
;;
"")
echo "You MUST input parameters, ex> {${0} someword}"
;;
*)
echo "Usage ${0} {hello}"
;;
esac
You MUST input parameters, ex> {aa.sh someword}
[root@localhost ~]# sh -x cc.sh \\可使用的輸出屏幕上
+ echo 'This program will print your selection !'
This program will print your selection !
+ case ${1} in
+ echo 'Usage cc.sh {one|two|three}'
Usage cc.sh {one|two|three}看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。