Linux Shell教程(一) 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

for循环

与其他编程语言类似,Shell支持for循环。

for循环一般格式为:

for 变量 in 列表
do
    command1
    command2
    ...
    commandN
done

列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。

in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。

范例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

范例2

顺序输出字符串中的字符:

#!/bin/bash
for str in This is a string
do
    echo $str
done

运行结果:

This                                                                             
is                                                                               
a                                                                                
string
编写shell脚本,倒序输出10-1。