How can I add an empty directory (that contains no files) to a Git repository?
Git does not track empty directories. See the Git FAQ for more explanation. The suggested workaround is to put a .gitignore
file in the empty directory. I do not like that solution, because the .gitignore
is "hidden" by Unix convention. Also there is no explanation why the directories are empty.
I suggest to put a README file in the empty directory explaining why the directory is empty and why it needs to be tracked in Git. With the README file in place, as far as Git is concerned, the directory is no longer empty.
The real question is why do you need the empty directory in git? Usually you have some sort of build script that can create the empty directory before compiling/running. If not then make one. That is a far better solution than putting empty directories in git.
So you have some reason why you need an empty directory in git. Put that reason in the README file. That way other developers (and future you) know why the empty directory needs to be there. You will also know that you can remove the empty directory when the problem requiring the empty directory has been solved.
To list every empty directory use the following command:
find -name .git -prune -o -type d -empty -print
To create placeholder READMEs in every empty directory:
find -name .git -prune -o -type d -empty -exec sh -c \
"echo this directory needs to be empty because reasons > {}/README.emptydir" \;
To ignore everything in the directory except the README file put the following lines in your .gitignore
:
path/to/emptydir/*
!path/to/emptydir/README.emptydir
path/to/otheremptydir/*
!path/to/otheremptydir/README.emptydir
Alternatively, you could just exclude every README file from being ignored:
path/to/emptydir/*
path/to/otheremptydir/*
!README.emptydir
To list every README after they are already created:
find -name README.emptydir