首页 > 编程笔记

Shell while循环的用法

while 命令允许定义一个要测试的命令,当测试命令返回的退出状态码为0时,循环执行一系列命令;在 test 命令返回非零退出状态码时,while 命令会停止执行那组命令。

while 命令的格式如下:

while test command
do
    other commands
done

while 命令主要在于所指定的 test command 的退出状态码必须跟随着循环中运行的命令而改变,如果退出状态码不发生改变,while循环将会一直执行下去。

while 命令还允许在 while 语句行定义多个测试命令,最后一个测试命令的退出状态码决定循环的结束时间。

【例 1】while 命令的使用。
使用 vim 编辑器打开脚本文件 test.sh,输入 i 命令进入插入模式,输入如下命令:

#!/bin/bash

var1=5

while echo $var1
    [ $var1 -ge 0 ]
do
    echo "inside the loop"
    var1=$[ $var1 - 1 ]
done

使用 sh(Bash)进程来执行脚本文件,输出结果为:

[root@bogon ~]# sh test.sh
5
inside the loop
4
inside the loop
3
inside the loop
2
inside the loop
1
inside the loop
0
inside the loop
-1

注意,最常见的 test command 的用法就是使用方括号检查循环命令中的 Shell 变量的值。

优秀文章