天天看點

Linux Shell流程控制

linux shell有一套自己的流程控制語句,其中包括條件語句(if),循環語句(for,while),選擇語句(case)。下面我将通過例子介紹下,各個語句使用方法。

一、shell條件語句(if用法)

if語句結構[if/then/elif/else/fi]

if 條件測試語句 

then 

action 

[elif 條件 

else 

fi  

如果對于:條件測試語句不是很清楚,可以參考:linux shell 邏輯運算符、邏輯表達式詳解

shell指令,可以按照分号分割,也可以按照換行符分割。如果想一行寫入多個指令,可以通過“’;”分割。

如:

[chengmo@centos5 ~]$ a=5;if [[ a -gt 4 ]] ;then echo 'ok';fi; 

ok  

執行個體:(test.sh)

#!/bin/sh 

scores=40; 

if [[ $scores -gt 90 ]]; then 

echo "very good!"; 

elif [[ $scores -gt 80 ]]; then 

echo "good!"; 

elif [[ $scores -gt 60 ]]; then 

echo "pass!"; 

echo "no pass!"; 

fi;     

Linux Shell流程控制

條件測試有:[[]],[],test 這幾種,注意:[[]] 與變量之間用空格分開。

二、循環語句(for,while,until用法)

for循環使用方法(for/do/done)

文法結構:

1. for … in 語句

for 變量 in seq字元串 

do 

done  

說明:seq字元串 隻要用空格字元分割,每次for…in 讀取時候,就會按順序将讀到值,給前面的變量。

執行個體(testfor.sh):

for i in $(seq 10); do 

echo $i; 

done; 

Linux Shell流程控制

seq 10 産生 1 2 3 。。。。10空格分隔字元串。

2.for((指派;條件;運算語句))

for((指派;條件;運算語句)) 

done;  

執行個體(testfor2.sh):

for((i=1;i<=10;i++));do 

Linux Shell流程控制

while循環使用(while/do/done)

while語句結構

while 條件語句 

執行個體1:

i=10; 

while [[ $i -gt 5 ]];do 

((i--)); 

運作結果:========================

sh testwhile1.sh

10

9

8

7

6

執行個體2:(循環讀取檔案内容:)

while read line;do 

echo $line; 

done < /etc/hosts;  

運作結果:===================

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

until循環語句

until 條件 

意思是:直到滿足條件,就退出。否則執行action.

執行個體(testuntil.sh):

a=10; 

until [[ $a -lt 0 ]];do 

echo $a; 

((a—)); 

結果:

sh testuntil.sh

5

4

3

2

1

三、shell選擇語句(case、select用法)

case選擇語句使用(case/esac)

文法結構

case $arg in   

    pattern | sample) # arg in pattern or sample   

    ;;   

    pattern1) # arg in pattern1   

    *) #default   

    ;;  

說明:pattern1 是正規表達式,可以用下面字元:

* 任意字串

? 任意字元

[abc] a, b, 或c三字元其中之一

[a-n] 從a到n的任一字元

| 多重選擇

執行個體:

case $1 in 

start | begin) 

    echo "start something"   

    ;; 

stop | end) 

    echo "stop something"   

*) 

    echo "ignorant"   

esac  

運作結果:======================

testcase.sh start

start something

select語句使用方法(産生菜單選擇)

文法:

select 變量name in seq變量

do    

    action 

select ch in "begin" "end" "exit" 

case $ch in 

"begin") 

"end") 

"exit") 

    echo "exit"   

    break; 

esac 

運作結果:

Linux Shell流程控制

說明:select是循環選擇,一般與case語句使用。

以上是shell的流程控制語句,條件,循環,選擇。 歡迎讨論交流!

作者:程默

來源:51cto

繼續閱讀