7

I have created the directory structure for my Maven project.

$ tree -a -I .git
.
├── .gitignore
├── README.md
├── pom.xml
└── src
 ├── main
 │  ├── java
 │  └── resources
 └── test
 ├── java
 └── resources
7 directories, 2 files

Now I'd like to persist the structure to .git, which requires creating dummy files in sub-directories. How can I (recursively) add empty .gitkeep files to all empty sub-directories?


Following questions already discuss (recursive) creation of empty files in sub-directories, but I'd like the files to be created only in leaf directories and not in any intermediate directories

asked Aug 16, 2018 at 18:42

2 Answers 2

10

From Ryan Armstrong's blog, here's how you do it with GNU find or compatible:

find . -type d -empty -not -path "./.git/*" -exec touch {}/.gitkeep \;
  • find . -type d (recursively) looks for directories under current path
  • -empty filters out directories that already contain something
  • -not -path "./.git/*" ensures no files are created inside .git directory
  • -exec touch {}/.gitkeep \; creates empty .gitkeep file in each directory matching above criteria

The resulting structure looks like

$ tree -a -I .git
.
├── .gitignore
├── README.md
├── pom.xml
└── src
 ├── main
 │  ├── java
 │  │  └── .gitkeep
 │  └── resources
 │  └── .gitkeep
 └── test
 ├── java
 │  └── .gitkeep
 └── resources
 └── .gitkeep
7 directories, 7 files
Stéphane Chazelas
583k96 gold badges1.1k silver badges1.7k bronze badges
answered Aug 16, 2018 at 18:42
0
0

With zsh:

() {touch -- $^@/.gitkeep} **/*(/^F)

Where:

  • **/: any amount (including 0) of subdirectories (recursive globing). Note that hidden files and directories are ignored by default.
  • (/^F): glob qualifiers with:
    • /: files of type directory
    • ^F: not Full (empty)
  • {} {body} arguments: anonymous functions:
  • $^@: $@ with rc_expand_param enabled so that $^@/.gitkeep expands to the same as 1ドル/.gitkeep 2ドル/.gitkeep... $n/.gitkeep instead of 1ドル 2ドル... $n/.gitkeep as it would do otherwise.
answered Jul 25, 2023 at 18:23

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.