Bash流程控制

keepcode發表於2020-04-28

1.if else

if語句

if condition
then
    command1
    command2
fi

if else語句

if condition
then
    command1
    command2
else
    command
fi

if elif else語句

if condition1
then
    command1
elif condition2
then
    command2
else
    command3
fi

2.for

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

3.while

while condition
do
    command
done

while中命令通常作為測試條件

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

while用於讀取鍵盤資訊

#!/bin/bash
echo 'press <CTRL-D> exit'
echo -n 'who do you think is the most hanssome: '
while read man
do
    echo "$man is really handsome"
done

無限迴圈

while :
do
    command
done

4.until

until condition
do
    command
done

5.case

case var in
parttern1)
    command1
    command2
    .....
    ;;
parttern2)
    command1
    command2
    ;;
esac

6.跳出迴圈

break

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

continue