Keeping Directories and editing gitignores: A Handy Alias
Git only tracks files, not directories, but sometimes you need to “track” a directory to ensure it exists in fresh clones, like an output folder.
A common pattern seen is using an empty .gitkeep file in this directory —
but this requires editing two places (the .gitkeep and your main
.gitignore), and if you rename the directory it’s easy to forget to update the
ignore rules.
The approach I use instead is summarised nicely
here by Adam
Johnson: use a .gitignore file inside the directory itself, containing * to
ignore everything, then !.gitignore to un-ignore the file so it gets
committed. This keeps the directory tracked with a single standard file that
survives renames.
Here’s a nice little alias I threw together in my ~/.gitconfig for this:
[alias]
ignore = "!f() { \
dir=\"${1:-.}\"; \
if [ ! -d $dir ]; then \
echo directory $dir not found ; \
exit 1; \
fi; \
gitignore=\"$dir/.gitignore\"; \
echo $gitignore; \
if [ ! -f $gitignore ]; then \
touch $gitignore; \
if [ $dir != '.' ]; then \
echo '*\n!.gitignore' >> $gitignore; \
fi; \
fi; \
$EDITOR $gitignore; \
}; f"Usage
# Create .gitignore in current directory
git ignore
# Create .gitignore in a specific directory
git ignore build/It creates the file with the two-line pattern from Adam’s post, then opens it in your editor so you can make any adjustments
Reply to this post by email blZake@proZbableodyssey.blog (remove Z characters) ↪