高級Bash腳本編程(六)筆記 [ 流程控制 if if-else for while until ]

if else

sh的流程控制不可爲空

1.if

if 語句語法格式:

if condition
then
    command1 
    command2
    ...
    commandN 
fi

2.if else

if else 語法格式:

if condition
then
    command1 
    command2
    ...
    commandN
else
    command
fi

if-elif-else 語法格式:

if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi

以下實例判斷兩個變量是否相等:

a=10
b=20
if [ $a == $b ]
then
   echo "a == b"
elif [ $a -gt $b ]
then
   echo "a > b"
elif [ $a -lt $b ]
then
   echo "a < b"
else
   echo "Ineligible"
fi

輸出結果:

a < b

if else語句經常與test命令結合使用

num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
    echo 'Two numbers are equal!'
else
    echo 'The two numbers are not equal!'
fi

輸出結果:

Two numbers are equal!

For語句

for循環一般格式爲:

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done

例如,順序輸出當前列表中的數字:

for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

輸出結果:

The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5

順序輸出字符串中的字符:

for str in This is a string
do
    echo $str
done

輸出結果:

This
is
a
string

while 語句

while循環用於不斷執行一系列命令,也用於從輸入文件中讀取數據;命令通常爲測試條件。其格式爲:

while condition
do
    command
done
#!/bin/bash
int=1
while(( $int<=5 ))
do
    echo $int
    let "int++"
done

運行腳本,輸出:

1
2
3
4
5
  • 如果int小於等於5,那麼條件返回真。int從1開始,每次循環處理時,int加1。運行上述腳本,返回數字1到5,然後終止。
    使用了 Bash let 命令,它用於執行一個或多個表達式,變量計算中不需要加上 $ 來表示變量
  • while循環可用於讀取鍵盤信息。下面的例子中,輸入信息被設置爲變量MAN,按結束循環。
echo 'press <CTRL-D> exit'
echo -n 'Who do you think is the most handsome: '
while read MAN
do
    echo "Yes!$MAN is really handsome"
done

無限循環語法格式:

while :
do
    command
done
或者
while true
do
    command
done

或者

for (( ; ; ))

until 循環

until循環執行一系列命令直至條件爲真時停止。 until循環與while循環在處理方式上剛好相反。 一般while循環優於until循環,但在某些時候—也只是極少數情況下,until循環更加有用。 until 語法格式:

until condition
do
    command
done

條件可爲任意測試條件,測試發生在循環末尾,因此循環至少執行一次—請注意這一點。

#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

until [ "${yn}" == "yes" -o "${yn}" == "YES" ]
do
    read -p "please input yes/YES to stop this program:" yn
done
echo "OK! you input the corret answer"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章