shell(八)循环

83 阅读1分钟

循环这个东西还是很重要的。比如说,给公司前端小姐姐秀一秀在控制台输出个爱心啥的啊,都是需要使用到循环的。

Shell编程中的循环有:for、while、utils,我们一个一个来看。

这里测试就能用到我们上一篇中看到的数组了,这个顺序,就很好~

测试循环也是在shell文件中测试的。

 

一:for循环

简单的看一下for循环的语法:

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

我们来测试一下:在she.sh中键入

#! /bin/bash
array=(1 2 3 4 5)
for item in array
do
        echo "当前参数值是:"$item
done

执行she.sh文件,输入如下所示:

[root@VM_0_4_centos test]# ./she.sh
当前参数值是:array

 

唉,这个和剧本写的不太一样啊,不是应该输出详情嘛

这样,修改一下程序吧

#! /bin/bash
arr=(1 2 3 4 5)
#for item in array
for item in 1 2 3 4 5
do
        echo "当前参数值是:$item"
done

再次执行she.sh文件,输出:

[root@VM_0_4_centos test]# ./she.sh
当前参数值是:1
当前参数值是:2
当前参数值是:3
当前参数值是:4
当前参数值是:5

 

For循环还可以循环输出字符串,测试一下:

#! /bin/bash
for item in be all you can be
do
        echo "当前参数值是:$item"
done

在控制台中执行she.sh,输出:

[root@VM_0_4_centos test]# ./she.sh
当前参数值是:be
当前参数值是:all
当前参数值是:you
当前参数值是:can
当前参数值是:be

 

二:while循环

我们先简单的看一下while的语法:

while condition
do
    command
done

测试一下,这部分仍然在shell文件中进行:

#! /bin/bash
number=1
while(( $number<=5 ))
do
        echo "当前的值为:$number"
        number=$[$number + 1]
done

在控制台中执行she.sh,输出:

[root@VM_0_4_centos test]# ./she.sh
当前的值为:1
当前的值为:2
当前的值为:3
当前的值为:4
当前的值为:5

 

三:until循环

Until在之前用过的语言中是没有用过的。

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

until 循环与 while 循环在处理方式上刚好相反。

一般 while 循环优于 until 循环,但在某些时候—也只是极少数情况下,until 循环更加有用。所以,until循环仅做了解就可以。

测试一下:

#! /bin/bash
nu=1
until [ ! $nu -lt 5 ]
do
        echo "当前的值为:$nu"
        nu=$[$nu + 1]
done

一定要注意书写格式,空格啥的可不能省。

执行she.sh,输出如下:

[root@VM_0_4_centos test]# ./she.sh
当前的值为:1
当前的值为:2
当前的值为:3
当前的值为:4

 

四:无限循环

Shell编程中的无限循环大概有三种写法,我这里展示一下示例,就不做测试了,服务器不行……

无限循环语法格式:

while :
do
    command
done

或者

while true
do
    command
done

或者

for (( ; ; ))

 

以上大概就是shell编程中的循环的基本使用。

有好的建议,请在下方输入你的评论。