在多个子目录中执行命令

Execute command in multiple sub-directories

假设我有这样的文件夹结构

- Parent Folder/
       - code.sh
       - Child Folder 1/
             - Child Sub-Folder/
       - Child Folder 2/
       - Child Folder 3/
       - Child Folder 4/

我需要某种 bash 脚本,它将被放置在 code.sh 中,并将 在子文件夹 1、子文件夹 2、子文件夹 3、子文件夹中执行命令文件夹 4 等 但不在 子文件夹中

到目前为止我只找到了这个解决方案

find ./* -mindepth 0 -maxdepth 0 -type d -exec git add -A {} \;

给我这个错误

fatal: not a git repository (or any of the parent directories): .git

当我尝试这个时

find ./* -mindepth 0 -maxdepth 0 -type d -exec git add -A && git commit -m "My Message"{} \;

给我这个错误

find: missing argument to `-exec'

任何帮助将不胜感激。

一种简单而可靠的方法,使用 parameter expansion:

#!/bin/bash

for dir in ./*/*/.git; do
    (
        cd "${dir%.git}"
        git add -A && git commit -m "My Message"
    )
done

确保您与 'Parent Folder' 目录处于同一级别。

一些解释:

  • 该代码段背后的想法是列出所有 .git 目录,其中包含 glob(通配符)./*/*/.git
  • ${dir%.git}bash参数扩展,去掉.git子串
  • subshell ( ) 是为了不必使用 cd 探索 FS 到下一个目录。每次迭代都是 运行 在一个新的 (sub)shell