Shell脚本中循环的使用(for和while部分)

part1:for 循环的实现

例如一个简单输出1-9的循环

方式1:类似于C语言的for循环

#C语音风格
for((i=1;i<10;i++))
do
    echo "the current number is $i"
done

echo "task is done!"

方式2: 类似于python语言中的for循环

#python语音风格
for i in {1..9}
do
    echo "the current number is $i"
done

echo "task is done!"

方式3: seq的使用

for i in $(seq 1 9)
do
    echo "the current number is $i"
done

echo "task is done!"

part2:while循环的使用

#while循环实现
i=1
#while [ $i -le 9 ]
while(($i<=9))
do
    echo "the current number is $i"
#    let i++
    i=$(($i+1))
done

echo "task is done!"

程序运行结果如下:

the current number is 1
the current number is 2
the current number is 3
the current number is 4
the current number is 5
the current number is 6
the current number is 7
the current number is 8
the current number is 9
task is done!

while循环几个需要注意的地方:

1. while 后面的条件语句的实现方式:

    (1)放在中括号[]内,且由一个空格隔开,例如上述的while [ $i -le 9 ],while与[]之间也由空格隔开;

    (2)使用两层小括号(()),中间不用空格;

2. while循环需要条件初始值和条件更改语句,此处是i=1和i自增1。i自增1此处有两种实现方式:

    (1)let i++

    (2)i=$(($i+1))

References:

1. https://blog.csdn.net/wdz306ling/article/details/79602739

2. http://c.biancheng.net/view/1006.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值