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

Git gc & Maintenance

git gc is like a spring cleaning that packs up loose papers into neat bundles so the project folder stays small and quick.
Syntax
bash
git count-objects -v
git gc [--prune=now]

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Running git gc --prune=now and expecting to keep recoverable commits, when it removes unreferenced objects permanently.
  2. Running git gc often out of habit, when Git already runs it automatically when needed.
  3. Expecting git gc to make the repository much smaller after committing large binaries, when the files remain in history.

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.