shell腳本及常用循環(huán)語句有哪些

shell腳本及常用循環(huán)語句有哪些,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來自于我們對(duì)這個(gè)行業(yè)的熱愛。我們立志把好的技術(shù)通過有效、簡(jiǎn)單的方式提供給客戶,將通過不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長(zhǎng)期合作伙伴,公司提供的服務(wù)項(xiàng)目有:申請(qǐng)域名、網(wǎng)頁(yè)空間、營(yíng)銷軟件、網(wǎng)站建設(shè)、懷來網(wǎng)站維護(hù)、網(wǎng)站推廣。

一.什么是shell及作用

Shell字面理解就是個(gè)“殼”,是操作系統(tǒng)(內(nèi)核)與用戶之間的橋梁,充當(dāng)命令解釋器的作用,將用戶輸入的命令翻譯給系統(tǒng)執(zhí)行。Linux中的shell與Windows下的DOS一樣,提供一些內(nèi)建命令(shell命令)供用戶使用,可以用這些命令編寫shell腳本來完成復(fù)雜重復(fù)性的工作

  • 什么是腳本?
    腳本就是由Shell命令組成的件,這些命令都是可執(zhí)行程序的名字,腳本不用編譯即可運(yùn)行。它通過解釋器解釋運(yùn)行,所以速度相對(duì)來說比較慢。

  • shell腳本的優(yōu)點(diǎn)

1.自動(dòng)化管理的重要依據(jù)
2.追蹤與管理系統(tǒng)的重要工
3.簡(jiǎn)單偵測(cè)功能
4.連續(xù)指令單一化
5.簡(jiǎn)易的數(shù)據(jù)處理
6.跨平臺(tái)支持與學(xué)習(xí)歷程較短

  • 編寫shell腳本注意事項(xiàng)

    1. 指令的執(zhí)行是從上而下、從左而右的分析與執(zhí)行;

    2. 指令的下達(dá)就如同之前提到的:指令、選項(xiàng)與參數(shù)間的多個(gè)空白都會(huì)被忽略掉;

    3. 空白行也將被忽略掉,并且 [tab] 按鍵所推開的空白同樣視為空白鍵;

    4. 如果讀取到一個(gè) Enter 符號(hào)(CR),就嘗試開始執(zhí)行該行(或該串)命令;

    5. 至于如果一行的內(nèi)容太多,則可以使用“ [Enter] ”來延伸至下一行;

    6. “ # ”可做為注解!任何加在 # 后面的數(shù)據(jù)將全部被視為注解字而被忽略!

  • 執(zhí)行shell腳本分為四點(diǎn)

直接指令下達(dá): shell.sh 件必須要具備可讀與可執(zhí)行(nx) 的權(quán)限,然后:
絕對(duì)路徑:使用/home/dtsai/shell.sh 來下達(dá)指令;
相對(duì)路徑:假設(shè)工作目錄在/home/dmtsai/,則使用.shel.sh 來執(zhí)行
*變量"PATH"功能:將shell.sh放在PATH指定的目錄內(nèi),例如: ~/bin/
以bash程序來執(zhí)行:通過“bash shell,sh”或“sh shell.sh "來執(zhí)行

二.簡(jiǎn)單編輯shell

[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
  1. 第一行 #!/bin/bash 在宣告這個(gè) script 使用的 shell 名稱:

  2. 程序內(nèi)容的說明:

  3. 主要環(huán)境變量的宣告:建議務(wù)必要將一些重要的環(huán)境變量設(shè)置好,我個(gè)人認(rèn)為, PATH 與 LANG (如果有使用到輸出相關(guān)的信息時(shí))是當(dāng)中最重要的!如此一來,則可讓我們這支程序在進(jìn)行時(shí),可以直接下達(dá)一些外部指令,而不必寫絕對(duì)路徑呢!

  4. 主要程序部分就將主要的程序?qū)懞眉纯?/p>

  5. 執(zhí)行成果告知(定義回傳值)一個(gè)指令的執(zhí)行成功與否,可以使用$?這個(gè)變量來觀察~那么我們也可以利用 exit 這個(gè)指令來讓程序中斷,并且回傳一個(gè)數(shù)值給系統(tǒng)

\a 發(fā)出警告聲; \n 換行且光標(biāo)移至行首;

對(duì)談式腳本:變量?jī)?nèi)容由使用者決定量
隨日期變化:利用date進(jìn)行件的創(chuàng)建
數(shù)值運(yùn)算:簡(jiǎn)單的加減乘除

對(duì)談式腳本:變量?jī)?nèi)容由使用者決定量

[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進(jìn)行件的創(chuàng)建

[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              \\可以看到創(chuàng)建了3天的件
20191203  20191205         a.sh  initial-setup-ks.cfg  公共  視頻  檔  音樂
20191204  anaconda-ks.cfg  b.sh  x.sh                  模板  圖片  下載  桌面
  • 數(shù)值運(yùn)算:簡(jiǎn)單的加減乘除

[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指令的測(cè)試功能

shell腳本及常用循環(huán)語句有哪些

shell腳本及常用循環(huán)語句有哪些

shell腳本及常用循環(huán)語句有哪些

shell腳本及常用循環(huán)語句有哪些

三.循環(huán)語句

  • if條件測(cè)試語句
    if條件測(cè)試語句可以讓腳本根據(jù)實(shí)際情況自動(dòng)執(zhí)行相應(yīng)的命令。從技術(shù)角度來講,if語句分為單分支結(jié)構(gòu)、雙分支結(jié)構(gòu)、多分支結(jié)構(gòu);其復(fù)雜度隨著靈活度一起逐級(jí)上升。
    1.if條件語句的單分支結(jié)構(gòu)由if、then、fi關(guān)鍵詞組成,而且只在條件成立后才執(zhí)行預(yù)設(shè)的命令,相當(dāng)于口語的“如果……那么……”。單分支的if語句屬于最簡(jiǎn)單的一種條件判斷結(jié)構(gòu)。

shell腳本及常用循環(huán)語句有哪些

案例:

[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 is

2.if條件語句的雙分支結(jié)構(gòu)由if、then、else、fi關(guān)鍵詞組成,它進(jìn)行一次條件匹配判斷,如果與條件匹配,則去執(zhí)行相應(yīng)的預(yù)設(shè)命令;反之則去執(zhí)行不匹配時(shí)的預(yù)設(shè)命令,相當(dāng)于口語的“如果……那么……或者……那么……”。if條件語句的雙分支結(jié)構(gòu)也是一種很簡(jiǎn)單的判斷結(jié)構(gòu)。

/upload/otherpic56/e6093221273e0d416b0ee944c5e318c4.jpg

還用上面的案例:

[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, continue

3.if條件語句的多分支結(jié)構(gòu)由if、then、else、elif、fi關(guān)鍵詞組成,它進(jìn)行多次條件匹配判斷,這多次判斷中的任何一項(xiàng)在匹配成功后都會(huì)執(zhí)行相應(yīng)的預(yù)設(shè)命令,相當(dāng)于口語的“如果……那么……如果……那么……”。if條件語句的多分支結(jié)構(gòu)是工作中最常使用的一種條件判斷結(jié)構(gòu),盡管相對(duì)復(fù)雜但是更加靈活。

shell腳本及常用循環(huán)語句有哪些

案例:

[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    \\可以看到必須加參數(shù)才能執(zhí)行
You MUST input parameters, ex> {a.sh someword}
[root@localhost ~]# sh a.sh hello
Hello, how are you ?

利用if... then:網(wǎng)絡(luò)狀態(tài)

[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})         \\偵測(cè)80端口是否存在
if [ "${testing}" != "" ]; then
echo "WWW is running in your system."
fi
testing=$(grep ":22 " ${testfile})          \\偵測(cè)22端口是否存在
if [ "${testing}" != "" ]; then
echo "SSH is running in your system."
fi
testing=$(grep ":21 " ${testfile})          \\偵測(cè)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正在系統(tǒng)中運(yùn)行
Mail is running in your system.                \\郵件服務(wù)正在系統(tǒng)中運(yùn)行
  • for條件循環(huán)語句
    for循環(huán)語句允許腳本一次性讀取多個(gè)信息,然后逐一對(duì)信息進(jìn)行操作處理,當(dāng)要處理的數(shù)據(jù)有范圍時(shí),使用for循環(huán)語句再適合不過了。

shell腳本及常用循環(huán)語句有哪些

for...do...done(固定循環(huán))

案例:
假設(shè)我有三種動(dòng)物,分別是 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條件循環(huán)語句
    while條件循環(huán)語句是一種讓腳本根據(jù)某些條件來重復(fù)執(zhí)行命令的語句,它的循環(huán)結(jié)構(gòu)往往在執(zhí)行前并不確定最終執(zhí)行的次數(shù),完全不同于for循環(huán)語句中有目標(biāo)、有范圍的使用場(chǎng)景。while循環(huán)語句通過判斷條件測(cè)試的真假來決定是否繼續(xù)執(zhí)行命令,若條件為真就繼續(xù)執(zhí)行,為假就結(jié)束循環(huán)。

shell腳本及常用循環(huán)語句有哪些

while... do...done,until...do...done(不定循環(huán))
While:當(dāng)滿足后面條件時(shí)才進(jìn)行循環(huán)
Until:當(dāng)不滿足后面條件時(shí)才進(jìn)行循環(huán)

案例:
假設(shè)我要讓使用者輸入 yes 或者是 YES 才結(jié)束程序的執(zhí)行,否則就一直進(jìn)行告知使用者輸入字串。

[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條件測(cè)試語句

case語句是在多個(gè)范圍內(nèi)匹配數(shù)據(jù),若匹配成功則執(zhí)行相關(guān)命令并結(jié)束整個(gè)條件測(cè)試;而如果數(shù)據(jù)不在所列出的范圍內(nèi),則會(huì)去執(zhí)行星號(hào)(*)中所定義的默認(rèn)命令。

shell腳本及常用循環(huán)語句有哪些

利用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 ”這個(gè)語法中,當(dāng)中的那個(gè)“ $變量 ”大致有兩種取得的方式:
直接下達(dá)式:例如上面提到的,利用“ script.sh variable ” 的方式來直接給予 $1 這個(gè)變量的內(nèi)容,這也是在 /etc/init.d 目錄下大多數(shù)程序的設(shè)計(jì)方式。
互動(dòng)式:通過 read 這個(gè)指令來讓使用者輸入變量的內(nèi)容。

讓使用者能夠輸入 one, two, three ,并且將使用者的變量顯示到屏幕上,如果不是 one, two, three 時(shí),就告知使用者僅有這三種選擇。

[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
  • 函數(shù)

函數(shù)的定義

        
     在shell 中有兩種定義函數(shù)的語法格式,分別為:

        函數(shù)名()
        {
          命令序列
          }

       或者:

        function 函數(shù)名()     /function 可以不寫
         {
          命令序列
          }

函數(shù)定義好后,用戶可以在shell 中直接調(diào)用,調(diào)用時(shí)不用帶上()

調(diào)用語法
          函數(shù)名   參數(shù)1   參數(shù)2 ....

 函數(shù)中的變量
           均為全局變量,沒有局部變量

 函數(shù)的調(diào)用
           可以傳遞參數(shù),在函數(shù)中用$1,$2, $3...來引用傳遞的參數(shù)。

還用上面的案例:用函數(shù)調(diào)用實(shí)現(xiàn)

[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'            \\將參數(shù)的大小寫轉(zhuǎn)換
        ;;   "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 TWO
  • Shell腳本的追蹤與debug

sh執(zhí)行的選項(xiàng)與參數(shù):

-n :不要執(zhí)行script(腳本),僅查詢語法的問題
-v :在執(zhí)行script前,先將腳本的內(nèi)容輸出到屏幕上
-x :將使用到的腳本內(nèi)容顯示到屏幕上,

案例:

[root@localhost ~]# sh -n aa.sh    \\不報(bào)錯(cuò)證明正常

[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}

看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)的支持。

當(dāng)前標(biāo)題:shell腳本及常用循環(huán)語句有哪些
當(dāng)前地址:http://muchs.cn/article4/gpjeoe.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供域名注冊(cè)、小程序開發(fā)、網(wǎng)站改版服務(wù)器托管、、微信公眾號(hào)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司