编写一个shell脚本,遍历当前文件夹下的所有文件。如果子文件夹下包含cmd.sh 就执行 sh cmd.sh
时间: 2024-03-18 22:39:47 浏览: 16
你可以使用以下 Shell 脚本来实现你的需求:
```bash
#!/bin/bash
# 遍历当前文件夹下所有文件和子文件夹
for file in $(find . -type f); do
# 如果子文件夹下包含 cmd.sh,则执行 sh cmd.sh
if [[ $file == */cmd.sh ]]; then
sh $file
fi
done
```
这个脚本会使用 `find` 命令遍历当前文件夹下的所有文件和子文件夹。对于每个找到的文件,如果它的路径包含 `/cmd.sh`,则执行 `sh cmd.sh` 命令。请注意,此脚本假定当前文件夹下没有空格或其他特殊字符的文件名。如果有这样的文件名,你需要修改脚本以正确处理它们。
相关问题
编写一个shell脚本,遍历当前文件夹下的所有文件。如果子文件夹下包含cmd.sh 就执行 sh cmd.sh。 a文件夹和b文件夹优先执行
你可以使用以下 Shell 脚本来实现你的需求:
```bash
#!/bin/bash
# 遍历 a 文件夹下所有文件和子文件夹,执行 cmd.sh
for file in $(find ./a -type f); do
if [[ $file == */cmd.sh ]]; then
sh $file
fi
done
# 遍历 b 文件夹下所有文件和子文件夹,执行 cmd.sh
for file in $(find ./b -type f); do
if [[ $file == */cmd.sh ]]; then
sh $file
fi
done
# 遍历其他文件夹下所有文件和子文件夹,执行 cmd.sh
for file in $(find . -type f); do
if [[ $file == */cmd.sh && $file != */a/* && $file != */b/* ]]; then
sh $file
fi
done
```
这个脚本会先遍历 `a` 文件夹下的所有文件和子文件夹,对于每个找到的文件,如果它的路径包含 `/cmd.sh`,则执行 `sh cmd.sh` 命令。然后它会遍历 `b` 文件夹下的所有文件和子文件夹,执行同样的操作。最后,它会遍历其他文件夹下的所有文件和子文件夹,对于每个找到的文件,如果它的路径包含 `/cmd.sh` 且不在 `a` 或 `b` 文件夹中,就执行 `sh cmd.sh` 命令。请注意,这个脚本同样假定当前文件夹下没有空格或其他特殊字符的文件名。如果有这样的文件名,你需要修改脚本以正确处理它们。
使用shell脚本。编写一个脚本。遍历当前文件夹下的所有文件夹。如果子文件夹包含cmd.sh 就进入子文件夹中执行 sh cmd.sh 直到所有文件夹都遍历完成
可以尝试使用以下脚本来实现:
```bash
#!/bin/bash
# 遍历当前文件夹下的所有子文件夹
for dir in $(find . -type d)
do
# 判断子文件夹中是否包含cmd.sh文件
if [ -f "$dir/cmd.sh" ]
then
# 进入子文件夹并执行cmd.sh
cd "$dir"
sh cmd.sh
cd ..
fi
done
```
解释一下脚本中的部分语句:
- `$(find . -type d)`:使用`find`命令遍历当前文件夹下所有子文件夹,并将结果传递给循环变量`dir`。
- `[ -f "$dir/cmd.sh" ]`:使用`[ -f ... ]`测试语句判断子文件夹中是否包含`cmd.sh`文件。
- `cd "$dir"`:使用`cd`命令进入子文件夹。
- `sh cmd.sh`:执行`cmd.sh`脚本。
- `cd ..`:返回上一级目录。
注意,该脚本需要放在需要遍历的文件夹中执行。可以使用`chmod +x script.sh`命令给脚本添加执行权限,然后使用`./script.sh`命令执行。