1、shell條件語句(if用法)linux
if語句結構[if/then/elif/else/fi]正則表達式
if 條件測試語句 then action [elif 條件 action else action ] fi
shell命令,能夠按照分號分割,也能夠按照換行符分割。若是想一行寫入多個命令,能夠經過「';」分割,如:shell
[chengmo@centos5 ~]$ a=5;if [[ a -gt 4 ]] ;then echo 'ok';fi;
實例:(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!"; else echo "no pass!"; fi;centos
2、循環語句(for,while,until用法):dom
(1)for循環使用方法(for/do/done)
1.for … in 語句——語法結構測試
for 變量 in seq字符串 # seq字符串 只要用空格字符分割,每次for…in讀取時候,就 會按順序將讀到值,給前面的變量。 do action done
實例(testfor.sh):ui
#!/bin/sh for i in $(seq 10); do #seq 10 產生 1 2 3 …… 10空格分隔字符串 echo $i; done;
2.for((賦值;條件;運算語句))教程
for((賦值;條件;運算語句)) do action done;
實例(testfor2.sh):rem
#!/bin/sh for((i=1;i<=10;i++));do echo $i; done;
(2)while循環使用(while/do/done)
while 條件語句 do action done;
實例1:
#!/bin/sh i=10; while [[ $i -gt 5 ]];do echo $i; ((i--)); done;
運行結果:
sh testwhile1.sh 10 9 8 7 6
實例2:(循環讀取文件內容:)
#!/bin/sh 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
(3)until循環語句——語法結構
until 條件 #直到知足條件,就退出。不然執行action. do action done
實例(testuntil.sh):
#!/bin/sh a=10; until [[ $a -lt 0 ]];do echo $a; ((a—)); done;
結果:
sh testuntil.sh 10 9 8 7 6 5 4 3 2 1 0
3、shell選擇語句(case、select用法)
(1)case選擇語句使用(case/esac)——語法結構
case $arg in pattern | sample) # arg in pattern or sample ;; pattern1) # arg in pattern1 ;; *) #default ;; esac
說明:pattern1 是正則表達式,能夠用下面字符:
* 任意字串 ? 任意字元
[abc] a, b, 或c三字元其中之一
[a-n] 從a到n的任一字元
| 多重選擇
實例:
#!/bin/sh case $1 in start | begin) echo "start something" ;; stop | end) echo "stop something" ;; *) echo "Ignorant" ;; esac
運行結果:
testcase.sh start start something
(2)select語句使用方法(產生菜單選擇)——語法
select 變量name in seq變量 do action done
實例:
#!/bin/sh select ch in "begin" "end" "exit" do case $ch in "begin") echo "start something" ;; "end") echo "stop something" ;; "exit") echo "exit" break; ;; *) echo "Ignorant" ;; esac done;
運行結果:
免費提供最新Linux技術教程書籍,爲開源技術愛好者努力作得更多更好:http://www.linuxprobe.com/