1. 程式人生 > >linux之bash指令碼流程控制

linux之bash指令碼流程控制

1.if語句

#!/bin/bash
if condition
then
command1
command2
fi

2.if else 語句

#!/bin/bash
if condition
then
command1
command2
else
command1
command2
fi

3.if-elif-else語句

#!/bin/bash
if condition
then
command1
command2
elif condition1
then
command3
command4
elif condition2
then
command5
else
command6
fi

例項

#!/bin/bash
a=10
b=20
if [ $a -eq $b ]
then
echo "a==b"
elif [ $a -gt $b ]
then
echo "a > b"
elif [ $a -lt $b ]
then
echo "a<b"
else
"..."
fi

輸出a<b

4.for語句

#!/bin/bash
for var in 1 3 6 
do
echo " the value is $var"
done

輸出
 the value is 1
 the value is 3
 the value is 6

5.while迴圈

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

Bash let 命令,它用於執行一個或多個表示式,變數計算中不需要加上 $ 來表示變數

6.無限迴圈

#!/bin/bash
while :
do
	command
done

for (( ; ; ))

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

#!/bin/bash
until condition
do
	command
done

8.case語句

相當於java中的switch語句
#!/bin/bash
read aNum
case $aNum in 1)
	echo 'You have chosen 1';;
	$aNum in 2)
	echo 'You have chosen 2';;
	$aNum in 3)
	echo 'You have chosen 3';;
	$aNum in *)
	echo 'You did not enter a number between 1 and 3';;
esac

取值後面必須為單詞in,每一模式必須以右括號結束。取值可以為變數或常數。匹配發現取值符合某一模式後,其間所有命令開始執行直至 ;;。
取值將檢測匹配的每一個模式。一旦模式匹配,則執行完匹配模式相應命令後不再繼續其他模式。如果無一匹配模式,使用星號 * 捕獲該值,再執行後面的命令
case相當於switch
* 相當於default

9.跳出迴圈
在迴圈過程中,有時候需要在未達到迴圈結束條件時強制跳出迴圈,Shell使用兩個命令來實現該功能:break和continue
break

#!/bin/bash
while :
do
    echo -n "Enter a number between 1 and 5:"
    read aNum
    case $aNum in
        1|2|3|4|5) echo "The number you entered is $aNum!"
        ;;
        *) echo "The number you entered is not between 1 and 5! game over!"
            break
        ;;
    esac
done

continue

continue命令與break命令類似,只有一點差別,它不會跳出所有迴圈,僅僅跳出當前迴圈

#!/bin/bash
while :
do
    echo -n "Enter a number between 1 and 5: "
    read aNum
    case $aNum in
        1|2|3|4|5) echo "The number you entered is $aNum!"
        ;;
        *) echo "The number you entered is not between 1 and 5!"
            continue
            echo "game over"
        ;;
    esac
done

case的語法和C family語言差別很大,它需要一個esac(就是case反過來)作為結束標記,每個case分支用右圓括號,用兩個分號表示break