shell 流程控制

一、 if else

if condition
then
    command1
else
    command2
fi

若else没有执行的语句,则不要写此else。

二、if else-if else

if condition1
then
    command1
elif condition2
then
    command2
else
    command3
fi

例如:

a=10
b=20

if [ $a -eq $b ]
then
    echo "a equal b"
elif [ $a -gt $b ]
then
    echo "a 大于 b"
elif [ $a -lt $b ]
then
    echo "a 小于 b"
else
    echo "no conditions"
fi

 

三、for循环

for循环一般格式为:

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

 

四、while语句

while condition
do
    command
done

 

五、until循环

until循环执行一系列命令直到条件为true时停止。

until condition
do command
done

例如:

#!/bin/sh

a=0

until [ ! $a -lt 10 ]
do
    echo $a
    a=`expr $a + 1`
done
输出
0
1
2
3
4
5
6
7
8
9

 

六、case

case语句为多选择语句。可以用case语句匹配一个值与一个模式,如果匹配成功,执行相匹配的命令。

casein
模式1)
    command1
    command2
    ;;    #相当于c++语言中的break
模式2)
    command3
    command4
    ;;
esac

例如:

echo "input 1-4 number:"
echo "input is: "
read aNum  #从输入流中读取,相当于c++中的cin >> aNum
case $aNum in
    1)
        echo "you choosed 1"
        ;;
    2)
        echo "you choosed2"
        ;;
esac

 

七、跳出循环

break 跳出此循环

continue 结束本次循环

两个命令的意义和c++中相同。

 

for循环也可以如下方式:

for((assignment;condition;next));
do
    command1
done;

for((i=1;i<=5;i++));do
    echo "this is $i called"
done;

 

posted @ 2018-12-28 11:41  c++11  阅读(188)  评论(0编辑  收藏  举报