一、shell條件語句(if用法)
if語句結構[if/then/elif/else/fi]
代碼如下:
if 條件測試語句
then
action
[elif 條件
action
else
action
]
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!";
else
echo "no pass!";
fi;
條件測試有:[[]],[],test 這幾種,注意:[[]] 與變量之間用空格分開。
二、循環語句(for,while,until用法):
1.for循環使用方法(for/do/done)
語法結構:
代碼如下:
1.for … in 語句
for 變量 in seq字符串
do
action
done
說明:seq字符串 只要用空格字符分割,每次for…in 讀取時候,就會按順序將讀到值,給前面的變量。
實例(testfor.sh):
代碼如下:
#!/bin/sh
for i in $(seq 10); do
echo $i;
done;
seq 10 產生 1 2 3 。。。。10空格分隔字符串。
2.for((賦值;條件;運算語句))
代碼如下:
for((賦值;條件;運算語句))
do
action
done;
實例(testfor2.sh):
代碼如下:
#!/bin/sh
for((i=1;i<=10;i++));do
echo $i;
done;
3.while循環使用(while/do/done)
while語句結構
代碼如下:
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
4.until循環語句
新聞熱點
疑難解答