Shell之流程控制

注:此博客使用的是Bash shell

if语句

  • if
if condition
then
    command1 
    command2
    ...
    commandN 
fi
  • if else
if condition
then
    command1 
    command2
    ...
    commandN
else
    command
fi
  • if else-if else
if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi

for循环

for var in vaule1 value2 ... valueN
do
	command
done
  • ②注意分号,for()里面用变量的时候,无需加$。但是,command里面用变量需要添加 $。
for((i=1;i<10;i++));do
	conmmand;
done;

while

temp=${1}

while [ ${temp} -gt 1 ]
do
        temp=`expr ${temp} - 1 `
        echo "${temp}"
done

无限循环

while :
do
	command
done
while true
do
	command
done

until循环

  • until 循环执行一系列命令直至条件为 true 时停止
  • until 循环与 while 循环在处理方式上刚好相反
  • 一般 while 循环优于 until 循环,但在某些时候—也只是极少数情况下,until 循环更加有用
#!/bin//bash
temp=${1}
until [ ${temp} -le 10 ]
do
        temp=`expr ${temp} - 1 `
        echo "${temp}"
done
cjs@Queue:~$ ./obj.sh 20
19
18
17
16
15
14
13
12
11
10

case

  • 类似C里面的switch
#!/bin/bash
read temp
case ${temp} in
	1) echo "1"
	;;
	2) echo "2"
	;;
	*) echo "无"
	;;
esac

跳出循环

  1. break命令(同C语言)
#!/bin/bash
while true
do
        echo "please input num"
        read temp
        case ${temp} in
                1|2|3|4|5) echo "cout ${temp}"
                ;;
                *) echo "this is great than 5"
                        break   #可以直接跳出while
                ;;
        esac
done
cjs@Queue:~$ ./obj.sh
please input num
1
cout 1
please input num
2
cout 2
please input num
3
cout 3
please input num
4
cout 4
please input num
5
cout 5
please input num
6
this is great than 5
  1. continue(同C语言)
#!/bin/bash
while true
do
        echo "please input num"
        read temp
        case ${temp} in
                1|2|3|4|5) echo "cout ${temp}"
                ;;
                *) echo "this is great than 5"
                        continue   #直接结束本次循环,开始下一次循环
                        echo "over"   #永远也无法运行到这句
                ;;
        esac
done
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋山刀名鱼丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值