在每个目录级别上运行脚本

问题描述 投票:0回答:3

我有一个名为summarize.sh的脚本,它生成目录中文件/目录的摘要。我想让它从顶部递归地沿着整个树运行。这是一个很好的方法吗?

我试图用for循环来循环它

for dir in */; do
cd $dir
./summarize.sh
cd ..

但它返回./summarize.sh:没有文件或目录是不是因为我在运行它时没有移动脚本?我对unix目录不太熟悉。

linux bash unix directory-structure
3个回答
1
投票

您可以使用find . -type f递归列出文件并使您的脚本将感兴趣的文件作为第一个参数,因此您可以执行find . -type f -exec myScript.sh {} \;

如果你只想要目录,请使用find . -type d,或者如果你想两者都使用find .而不受限制。

按名称的附加选项,例如find . -name '*.py'

最后,如果你不想递归目录结构,即只汇总顶层,你可以使用-maxdepth 1选项,所以像find . -type d -maxdepth 1 -exec myScript.sh {} \;


1
投票

问题是您使用cd命令更改到其他目录,而summaryrize.sh脚本不在这些目录中。一种可能的解决方案是使用绝对路径而不是相对路径。例如,更改:

./summarize.sh

类似于:

/path/to/file/summarize.sh

或者,在给定的示例代码下,您还可以使用指向上一个目录的相对路径,如下所示:

../summarize.sh

0
投票

如果您运行的是Bash 4.0或更高版本,请尝试使用此代码:

#! /bin/bash -p

shopt -s nullglob   # Globs expand to nothing when they match nothing
shopt -s globstar   # Enable ** to expand over the directory hierarchy

summarizer_path=$PWD/summarize.sh

for dir in **/ ; do
    cd -- "$dir"
    "$summarizer_path"
    cd - >/dev/null
done
  • shopt -s nullglob避免在当前目录下没有目录时出错。
  • summarizer_path变量设置为summarize.sh程序的绝对路径。这是允许它在当前目录以外的目录中运行所必需的。 (./summarize.sh仅适用于当前目录,.。)
  • 如果任何目录名称以“ - ”开头,请使用cd -- ...以避免出现问题。
  • cd - >/dev/nullcd到上一个目录,并在cd -输出时扔掉它的路径。
  • Shellcheck发布了关于上述代码的几个警告,所有这些都与使用cd有关。我会修复它们的“真实”代码。
© www.soinside.com 2019 - 2024. All rights reserved.