In the previous tutorial, we’ve learned How to create empty commits in Git. Let’s see how can we remove them as well.
Prerequisites
- Git
Solution
Step 1. Once you’ve created an empty commit (if not, run git commit --allow-empty -m "Test empty commit"
), try to list empty commits only.
git rev-list HEAD | while read commitHash; do
if [ $(git diff-tree --name-status --no-commit-id $commitHash | wc -l) -eq 0 ]; then
echo $commitHash
fi;
done
Example hash value output from the empty commit:
af4c5c59e2cbd56385a0c7103b198e54df07464f
Step 2. Remove empty commits.
git filter-branch --commit-filter 'git_commit_non_empty_tree "$@"' -f HEAD
rm -rf .git/refs/original/ && git reflog expire --all && git gc --aggressive --prune
Parameters:
-filter-branch
: Allows you to rewrite branches.-commit-filter
: Filter for performing the commit.git_commit_non_empty_tree "$@"
: Including this parameter with -commit-filter will skip commits that leave the tree untouched. Tree hash stays the same if no files are changed, hence the empty commit.-f
: Short for--force
.
Step 3. Confirm the empty commit removal, by executing the command in Step 1
again.
Conclusion
If something goes wrong, just rm -rf
the repository and clone it again (just kidding). To find more neat Git commands and hacks, browse the Git category. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.