您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页Shell Script(七):循环(for, while, u

Shell Script(七):循环(for, while, u

来源:伴沃教育

       本文主要通过实例来介绍 for,while 和 until 三种循环方式的使用方式。

       一、for 的使用
       for 循环的一般格式为:

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

       其中 in 列表中的每个 item 可以是字符串或位置参数 ,关于位置参数会在后面的文章中介绍。先看两个实例来直观感受一下。
       1、 第一个实例

#!/bin/bash
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

       注意这个实例里面 in 列表中的 1 2 3 4 5 是字符串的形式。

       2、 第二个实例

#!/bin/bash
for str in 'Good morning' 'Nice to meet you'
do
    echo $str
done

输出结果如下:

Good morning
Nice to meet you

       二、 while 循环
       while 循环的基本形式如下:

while condition
do
    command
done

实例如下:

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

输出结果如下:

1
2
3
4
5

       三、until 循环
       其使用方式如下:

until condition
do
    command
done

注意:在 until 循环中,condition 为 false 的时候 do 和 done 之间的 command 才会被执行。当 condition 为 true 时,until 循环会被终止,这个逻辑是和 for 以及 while 循环相反的。

       四、无限循环
       如果用到了无限循环的逻辑,那么代码可以写成下面的几种形式:
第一种:

for (( ; ; ))

第二种:

while :
do
    command
done

第三种:


while true
do
    command
done

相关文档

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务