How to remove empty commits in Git

Aug 27, 2021 · 1 min read · Post a comment

In the previous tutorial, we’ve learned How to create empty commits in Git. Let’s see how can we remove them as well.


  • Git


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

Example hash value output from the empty commit:


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


  • -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.


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.