Linux中for循环用于重复执行命令,常见于批量创建用户、处理文件列表等场景,支持通过seq生成序列、数组遍历、通配符匹配文件及结合continue/break控制流程。

Linux中循环处理,本质上就是重复执行一系列命令,直到满足特定条件为止。这在自动化脚本、数据处理、系统管理等方面非常有用。
Linux下的循环主要有
for
while
until
for
while
until
for
for
for variable in list do commands done
variable
list
variable
list
commands
list
实战例子:批量创建用户
假设我们需要批量创建用户,用户名从
user1
user10
for i in $(seq 1 10) do useradd user$i echo "user$i:password" | chpasswd done
这里
seq 1 10
user$i
i
user
chpasswd
password
进阶用法:处理文件列表
for
for file in *.txt do echo "Processing file: $file" # 这里可以添加处理文件的命令,比如 grep, sed, awk 等 grep "keyword" $file done
这个例子会遍历当前目录下所有以
.txt
grep
keyword
关于空格和引号
在处理包含空格的文件名时,需要特别注意。如果文件名包含空格,需要使用引号将文件名括起来,否则
for
for file in *"My Document"* do echo "Processing file: \"$file\"" done
这里假设有一个文件名叫做 "My Document.txt",使用
*"My Document"*
$file
通配符是 Linux 中非常强大的工具,可以用来匹配文件名。常见的通配符包括
*
?
[]
例如,要处理当前目录下所有以
.log
*.log
for file in *.log do echo "Processing log file: $file" # 这里可以添加处理日志文件的命令,比如分析日志、统计错误等 done
如果要处理文件名以数字开头的文件,可以使用
[0-9]*
for file in [0-9]* do echo "Processing file: $file" done
通配符还可以组合使用,例如
*[0-9].txt
.txt
使用通配符需要注意转义特殊字符,例如
*
?
[]
\
数组是存储多个值的变量。在
for
定义数组的语法如下:
array=(value1 value2 value3)
可以使用索引来访问数组中的元素,索引从 0 开始。例如,
array[0]
在
for
${array[@]}${array[*]}my_array=(item1 item2 item3)
for item in "${my_array[@]}"
do
echo "Processing item: $item"
done这个例子会遍历
my_array
${#my_array[@]}echo "Array length: ${#my_array[@]}"数组在处理配置信息、参数列表等方面非常有用。
seq
seq
seq
seq [FIRST] [INCREMENT] LAST
FIRST
INCREMENT
LAST
例如,
seq 1 2 10
在
for
seq
for i in $(seq 1 10) do echo "Processing number: $i" done
这个例子会生成一个从 1 到 10 的数字序列,并输出每个数字。
seq
seq 0.1 0.1 1.0
这个命令会生成一个从 0.1 到 1.0 的浮点数序列,步长为 0.1。
seq
在某些情况下,可能需要在
for
continue
break
continue
for i in $(seq 1 10)
do
if [ $i -eq 5 ]; then
continue # 跳过 i 等于 5 的迭代
fi
echo "Processing number: $i"
done这个例子会输出 1 2 3 4 6 7 8 9 10,跳过了 5。
break
for i in $(seq 1 10)
do
if [ $i -gt 5 ]; then
break # 提前结束循环,当 i 大于 5 时
fi
echo "Processing number: $i"
done这个例子会输出 1 2 3 4 5,当 i 大于 5 时,循环结束。
continue
break
for
$(command)
command
例如,要遍历当前目录下所有子目录,可以使用
ls -d */
for
for dir in $(ls -d */) do echo "Processing directory: $dir" # 这里可以添加处理目录的命令,比如统计文件数量、备份目录等 done
需要注意的是,如果命令的输出包含空格或换行符,需要使用引号将命令替换括起来,否则
for
for file in "$(find . -type f)" do echo "Processing file: $file" done
这个例子会使用
find
命令替换在处理动态数据、自动化脚本等方面非常有用。
以上就是如何在Linux中循环处理 Linux for循环实战应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号