您好,登錄后才能下訂單哦!
這篇文章主要介紹“Linux shell流程控制實(shí)例分析”,在日常操作中,相信很多人在Linux shell流程控制實(shí)例分析問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Linux shell流程控制實(shí)例分析”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
if語句結(jié)構(gòu)[if/then/elif/else/fi]
if 條件測試語句thenaction [elif 條件 actionelseaction ]fi
shell命令,可以按照分號分割,也可以按照換行符分割。如果想一行寫入多個命令,可以通過“’;”分割,如:
[chengmo@centos5 ~]$ a=5;if [[ a -gt 4 ]] ;then echo 'ok';fi;
實(shí)例:(test.sh)
#!/bin/shscores=40;if [[ $scores -gt 90 ]]; thenecho "very good!";elif [[ $scores -gt 80 ]]; thenecho "good!";elif [[ $scores -gt 60 ]]; thenecho "pass!";elseecho "no pass!";fi;
(1)for循環(huán)使用方法(for/do/done) 1.for … in 語句——語法結(jié)構(gòu)
for 變量 in seq字符串 # seq字符串 只要用空格字符分割,每次for…in讀取時候,就 會按順序?qū)⒆x到值,給前面的變量。doactiondone
實(shí)例(testfor.sh):
#!/bin/shfor i in $(seq 10); do #seq 10 產(chǎn)生 1 2 3 …… 10空格分隔字符串echo $i;done;
2.for((賦值;條件;運(yùn)算語句))
for((賦值;條件;運(yùn)算語句))doactiondone;
實(shí)例(testfor2.sh):
#!/bin/shfor((i=1;idoecho $i;done;
(2)while循環(huán)使用(while/do/done)
while 條件語句doactiondone;
實(shí)例1:
#!/bin/shi=10;while [[ $i -gt 5 ]];doecho $i; ((i--));done;
運(yùn)行結(jié)果:
sh testwhile1.sh 10 9 8 7 6
實(shí)例2:(循環(huán)讀取文件內(nèi)容:)
#!/bin/shwhile read line;doecho $line;done
運(yùn)行結(jié)果:
sh testwhile2.sh# Do not remove the following line, or various programs# that require network functionality will fail.127.0.0.1 centos5 localhost.localdomain localhost
(3)until循環(huán)語句——語法結(jié)構(gòu)
until 條件 #直到滿足條件,就退出。否則執(zhí)行action.doactiondone
實(shí)例(testuntil.sh):
#!/bin/sha=10; until [[ $a -lt 0 ]];doecho $a; ((a—));done;
結(jié)果:
sh testuntil.sh 10 9 8 7 6 5 4 3 2 1 0
(1)case選擇語句使用(case/esac)——語法結(jié)構(gòu)
case $arg inpattern | sample) # arg in pattern or sample;; pattern1) # arg in pattern1;; *) #default;;esac
?
說明:pattern1 是正則表達(dá)式,可以用下面字符: * 任意字串 ? 任意字元 [abc] a, b, 或c三字元其中之一 [a-n] 從a到n的任一字元 | 多重選擇
實(shí)例:
#!/bin/shcase $1 instart | begin)echo "start something";; stop | end)echo "stop something";; *)echo "Ignorant";;esac
運(yùn)行結(jié)果:
testcase.sh start start something
(2)select語句使用方法(產(chǎn)生菜單選擇)——語法
select 變量name in seq變量doactiondone
實(shí)例:
#!/bin/shselect ch in "begin" "end" "exit"docase $ch in"begin")echo "start something";;"end")echo "stop something";;"exit")echo "exit"break; ;; *)echo "Ignorant";;esacdone;
運(yùn)行結(jié)果:
到此,關(guān)于“Linux shell流程控制實(shí)例分析”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。