6.shell的控制流程

一、if else

1.if

if语句语法格式

if a

then

 command1

 command1 command1

fi

2.if else

if condition

 then

   command1

 command1 command1

else

 commad

fi

3.if else - if else

if condition1

then

 command1

elif condition2

then

 command2

else 

 commandN

fi

二 .for 循环

一般格式

for var in item item2 ....iteN

do 

  command1

  command2

...

done

写成一行

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

当变量值在列表里,for循环即执行一次所有命令,使用变量名获取列表中的当前取值。命令可为任何有效的shell命令和语句。in列表可以包含替换、字符串和文件名。

in列表是可选的,如果不用它,for循环使用命令行的位置参数。

例如,顺序输出当前列表中的数字:

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

三while循环

while循环用于不断执行一系列命令,也用于从输入文件中读取数据;命令通常为测试条件.其格式为:

while condition

do

  command

done

以下是一个基本的while循环,测试条件是:如果int小于等于5,那么条件返回真。int从0开始,每次循环处理时,int加1。运行上述脚本,返回数字1到5,然后终止。

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

无线循环

格式:

while:

do

   command

done

或者

while true

do 

   command

done

或者 for(( ; ;  ))

四 until循环

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

格式:

until condition

do

   command

done

五.case

 shell case语句为多选择语句.可以用来进行语句匹配

格式:

case  值   in

模式1)

command1

command2

...

commandN

;;

模式2)

command1

command2

...

commandN

;;

esac

 

case工作方式如上所示,取值后面必须为单词in,每一模式必须以右括号结束.取值可以为变量或常数.匹配发现 取值符合某一模式后,期间所有命令开始执行直至;;.

取值将检测匹配的每一个模式.一旦模式匹配,则执行完匹配模式相应命令后不再继续其他模式.如果无一匹配模式,使用*捕获该值,再执行后面的命令.

echo '输入 1 到 4 之间的数字:'
echo '你输入的数字为:'
read aNum
case $aNum in
    1)  echo '你选择了 1'
    ;;
    2)  echo '你选择了 2'
    ;;
    3)  echo '你选择了 3'
    ;;
    4)  echo '你选择了 4'
    ;;
    *)  echo '你没有输入 1 到 4 之间的数字'
    ;;
esac

输出

输入 1 到 4 之间的数字:
你输入的数字为:
3
你选择了 3

六 跳出循环

在循环过程中,有时候需要在为达到循环结束条件时强制跳出循环,shell使用两个命令来实现该功能,break和continue

1.break

break 命令允许跳出所有循环(终止执行后面的所有循环)

#!/bin/bash
while :
do
    echo -n "输入 1 到 5 之间的数字:"
    read aNum
    case $aNum in
        1|2|3|4|5) echo "你输入的数字为 $aNum!"
        ;;
        *) echo "你输入的数字不是 1 到 5 之间的! 游戏结束"
            break
        ;;
    esac
done

2.continue

continue命令与break命令类似,只有一点差别,他不会跳出所有循环,只会跳出当前循环

3.case ...esac

case ... esac 与其他语言中的 switch ... case 语句类似,是一种多分枝选择结构,每个 case 分支用右圆括号开始,用两个分号 ;; 表示 break,即执行结束,跳出整个 case ... esac 语句,esac(就是 case 反过来)作为结束标记。

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值