Skip to content

Instantly share code, notes, and snippets.

@oyvholm
Created May 30, 2010 13:27
Show Gist options
  • Save oyvholm/419015 to your computer and use it in GitHub Desktop.
Save oyvholm/419015 to your computer and use it in GitHub Desktop.
Workaround for storing empty directories in Git
This is a workaround for storing empty directories in Git.
People have suggested things like storing empty .gitignore files in every empty
directory, but sometimes this is not something we want to do. Instead, use
git-store-dirs to create a file named ".emptydirs" at the top of the working
tree that contains a null-separated list of all empty directories, and use
git-restore-dirs to get them all back.
#!/bin/sh
# git-restore-dirs
# Restore empty directories created by git-store-dirs(1)
dirfile=.emptydirs
test -d .git/. || { echo $0: Has to be run from the toplevel of the working tree >&2; exit 1; }
test -e $dirfile || { echo $0: No $dirfile file found >&2; exit 1; }
xargs -0 mkdir -p <$dirfile
#!/bin/sh
# git-store-dirs
# Store a list of all directories to $dirfile to be able to restore empty
# directories. The list is \0-separated in case there are some directory names
# containing (ugh) \n. Use git-restore-dirs(1) to recreate directories.
dirfile=.emptydirs
test -d .git/. || { echo $0: Has to be run from the toplevel of the working tree >&2; exit 1; }
find -type d -empty -print0 | grep -E -v -z '/\.git(/|$)' | LC_ALL=C sort -z >$dirfile
test "$(cat $dirfile)" = "" &&
(
git reset $dirfile
rm $dirfile
echo "$0: No empty directories found, deleting $dirfile" >&2
) || git add $dirfile
@DeveloperChris
Copy link

another workaround

before adding to git

find ./ -type d -empty ! -regex './.git/.*' -exec touch {}/.empty ;

then git add . (if that suits)

after restore delete the .empty files, only deletes .empty files that are actually empty.

find ./ -type f -name .empty -empty -exec rm {} ;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment