本帖最后由 风精灵 于 2026-3-18 09:33 编辑

1. for循环
shell中的for循环语句语法如下:
for 变量名 in 取值范围
for var in ele0 ele1…eleN
do
   command
done
以上示例,$var的变量内容在循环工作时:
1次循环时,$var的内容为ele0
2次循环时,$var的内容为ele1
... ...
N次循环时,$var的内容为eleN
举例在myshell.sh中加入如下内容:
#!/bin/bash
echo "my first shell !"
for i in 1 2 3 4 5 6
do
        echo $(expr $i \* 2)
done
图片2.png
执行结果如下:
图片3.png
对于上面变量值为数字的情况,其取值范围还可以有以下几种表示方式:
for((i=1;i<=6;i++))
for i in $(seq 1 6 1)
for i in {1..6..1}
2. while循环
shell中的while循环语句语法如下,condition为判断式,command为程序段落。
while condition
do
command
done
举例:
#!/bin/bash
echo "my first shell !"
i=0
while(($i < 6))
do      
        echo $(expr $i \* 2)
        let i++
done
图片4.png
执行结果如下:
图片5.png
当判断式为空,写成:
while true
while :
此时,则为无限循环。
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    Powered by Discuz! X3.5  © 2001-2013 Comsenz Inc.