← Back to Git Course | Chapter 10: Tools & Internals | Lesson 5 of 8

Git gc & Maintenance

What is Git Garbage Collection?

As you modify and delete files, Git accumulates loose, unreferenced objects and legacy history fragments. Garbage collection compresses these files into packed files, optimizing repository size and speed.

Example: What is Git Garbage Collection?

bash
git count-objects -v

Running git gc

git gc bundles loose objects into compressed pack files and removes objects that are no longer referenced by anything, shrinking the .git directory and speeding up operations that scan history — most repositories never need to run it manually since Git triggers it automatically past certain thresholds.

Example: Running git gc

bash
git gc

Pruning Loose Objects

Objects left over from a discarded commit, an aborted rebase, or a deleted branch stick around until they're pruned — git prune removes any object no longer reachable from a branch, tag, or the reflog, freeing the disk space they were taking up.

Example: Pruning Loose Objects

bash
git prune

Checking Repository Health

git fsck walks every object in the repository's database checking for corruption or dangling references (objects that exist but nothing points to), which is the tool to reach for if a repository starts behaving strangely and you suspect the underlying data itself is damaged.

Example: Checking Repository Health

bash
git fsck

Automated Background Maintenance

Since Git 2.30, git maintenance can schedule background tasks — prefetching, incremental repacking, loose-object cleanup — to run periodically without you remembering to invoke gc yourself, keeping large, long-lived repositories fast without manual upkeep.

Example: Automated Background Maintenance

bash
git maintenance start

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.