前言

Linuxfor循环是一种常用的控制结构,它可以在Shell脚本中重复执行一系列命令,以便对一组数据进行操作。以下是一些常用的for循环案例及使用事项

案例

遍历文件列表:可以使用for循环来遍历一个目录中的所有文件

#!/bin/bash
for file in /path/to/directory/*
do
echo $file
done

遍历数字列表:for循环可以用于遍历数字列表

#!/bin/bash
for i in {1..10}
do
echo $i
done

遍历命令输出:可以使用for循环来遍历一个命令的输出结果

#!/bin/bash
for user in $(cat /etc/passwd | awk -F ':' '{print $1}')
do
echo $user
done

多重循环:for循环可以嵌套使用,实现多重循环

#!/bin/bash
for i in {1..5}
do
for j in {1..3}
do
echo "$i,$j"
done
done

输出1到100之间所有质数的和

#!/bin/bash
sum=0
for i in {2..100}
do
is_prime=1
for ((j=2; j<i; j++))
do
if [ $((i % j)) -eq 0 ]
then
is_prime=0
break
fi
done
if [ $is_prime -eq 1 ]
then
sum=$((sum + i))
fi
done
echo "The sum of prime numbers from 1 to 100 is: $sum"

打印给定目录下的文件数

#!/bin/bash
dir="/path/to/directory"
count=0
for file in $dir/*
do
if [ -f $file ]
then
count=$((count + 1))
fi
done
echo "The number of files in $dir is: $count"

批量修改文件名

#!/bin/bash
# 将当前目录下所有的 .txt 文件名中的 "abc" 替换成 "def"
for file in *.txt
do
mv "$file" "${file/abc/def}"
done

批量复制文件

#!/bin/bash
# 复制当前目录下所有的 .txt 文件到 /tmp 目录下
for file in *.txt
do
cp "$file" /tmp/
done

批量压缩文件

#!/bin/bash
# 将当前目录下所有的 .txt 文件压缩成 .tar.gz 格式
for file in *.txt
do
tar czf "${file}.tar.gz" "$file"
done

批量解压文件

#!/bin/bash
# 将当前目录下所有的 .tar.gz 文件解压到 /tmp 目录下
for file in *.tar.gz
do
tar xzf "$file" -C /tmp/
done

批量部署应用

#!/bin/bash
# 部署多个应用到不同的目录下
apps=(app1 app2 app3 app4 app5)
for app in "${apps[@]}"
do
mkdir "/var/www/${app}"
cp -r "/tmp/${app}"/* "/var/www/${app}/"
done

使用事项

  • for循环语法:for variable in values; do commands; done
  • 变量可以是任何字符序列,但通常是单个字符
  • 值可以是一组文件、数字、命令输出等
  • 多个值之间使用空格分隔
  • 命令输出必须使用$(command)或反引号来括起来
  • 在执行循环体时,必须使用done关键字来结束循环体

总之,for循环是一个非常实用的Linux脚本结构,可以帮助您遍历文件、数字、命令输出等。使用它可以简化重复的任务,提高工作效率。