Shell命令學習(四)

Shell 流程控制

if else

if語句格式:

if condition
then
    command1
    command2
    ...
    commandN
fi

if else語句格式

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

實例:

#!/bin/bash
a=20
b=30
if [ $a == $b ]
then
        echo "a等於b"
elif [ $a -lt $b ]
then
        echo "a小於b"
elif [ $a -gt $b ]
then
        echo "a大於b"
else
        echo "沒有符合的條件"
fi

運行結果:
運行結果

if語句常與test合用:

#!/bin/bash
mytijian=$[3*3]
hywang=$[6+3]
if test $[mytijian] -eq $[hywang]
then
        echo "兩個數字相等"
else
        echo "兩個數字不相等"
fi

運行結果:
運行結果

for循環

for循環的一般格式:

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

寫成一行:

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

實例:

#!/bin/bash
for mytijianloop in 1 2 3 4 5
do
        echo "The value of mytijianloop: $mytijianloop"
done

運行結果:
運行結果

while語句

while的一般格式:

while condition
do
    command
done

實例:

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

運行結果:
運行結果
注:
while循環可用於讀取鍵盤信息。

#!/bin/bash
echo "按下<CTRL-D>退出"
echo -n "輸入mytijian:"
while read mytijian
do
        echo "$mytijian"
done

輸入mytijian的值後,回車顯示剛剛輸入的值,按下CTRL+D退出
運行結果:
運行結果

until循環

until循環的一般格式:

until condition
do
    command
done

case

case語句一般格式如下:

case 值 in 
模式1)
    command1
    command2
    ;;
模式2)
    command3
    command4
    ;;
esac

實例:

#!/bin/bash
echo "輸入1到4之間的數字:"
read aNum
case $aNum in
        1)
                echo "你輸入了1"
                ;;
        2)
                echo "你輸入了2"
                ;;
        3)
                echo "你輸入了3"
                ;;
        4)
                echo "你輸入了4"
                ;;
        *)
                echo "你輸入的數字不符合條件"
                ;;
esac

運行結果:
運行結果

跳出循環

break

break命令允許跳出所有循環(終止執行後面的所有循環)
實例:

#!/bin/bash
while :
do
        echo -n "輸入1至5的數字:"
        read num
        case $num in
                1|2|3|4|5)
                        echo "你輸入的數字爲: $num!"
                        ;;
                *)
                        echo "你輸入的數字不是1至5之間的數字"
                        break
                        ;;
        esac
done

這個例子是讓用戶一直輸入一個1到5的數字,知道輸入不在1至5之間的數字,跳出整個循環
運行結果:
運行結果

continue

continue只是跳出當前循環
實例:

#!/bin/bash
while :
do
        echo -n "輸入1到5之間的數字:"
        read num
        case $num in
                1|2|3|4|5)
                        echo "你輸入的數字爲: $num!"
                        ;;
                *)
                        echo "你輸入的輸在不在1到5之間"
                        continue
                        echo "Game Over"
                        ;;
        esac
done

運行結果:
運行結果
echo “Game Over”永遠不會執行

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章