0
0
Gitdevops~5 mins

Garbage collection with git gc - Commands & Configuration

Choose your learning style9 modes available
Introduction
Git stores many objects as you work, like commits and files. Over time, some objects become unused and take up space. The git gc command cleans up these unused objects to keep your repository fast and small.
When your repository feels slow or large after many commits and branches.
When you want to free up disk space used by old, unneeded data in your git repository.
After deleting branches or rewriting history to remove old commits.
Before making a backup to reduce the size of the repository.
When git suggests running garbage collection to optimize performance.
Commands
This command runs garbage collection to clean up unnecessary files and optimize the local repository.
Terminal
git gc
Expected OutputExpected
Enumerating objects: 50, done. Counting objects: 100% (50/50), done. Delta compression using up to 8 threads Compressing objects: 100% (30/30), done. Writing objects: 100% (50/50), done. Total 50 (delta 20), reused 0 (delta 0) Removing duplicate objects
Runs a more thorough garbage collection that takes longer but can save more space by compressing objects better.
Terminal
git gc --aggressive
Expected OutputExpected
Enumerating objects: 50, done. Counting objects: 100% (50/50), done. Delta compression using up to 8 threads Compressing objects: 100% (30/30), done. Writing objects: 100% (50/50), done. Total 50 (delta 20), reused 0 (delta 0) Removing duplicate objects
--aggressive - Makes garbage collection more thorough and compresses objects better
Removes all unreachable objects immediately instead of waiting for the default grace period.
Terminal
git gc --prune=now
Expected OutputExpected
Enumerating objects: 50, done. Counting objects: 100% (50/50), done. Delta compression using up to 8 threads Compressing objects: 100% (30/30), done. Writing objects: 100% (50/50), done. Total 50 (delta 20), reused 0 (delta 0) Pruning all unreachable objects now
--prune=now - Deletes unreachable objects immediately
Key Concept

If you remember nothing else from this pattern, remember: git gc cleans up unused data to keep your repository fast and small.

Common Mistakes
Running git gc too often or on very large repositories without understanding the time it takes.
Aggressive garbage collection can take a long time and slow down your work if run unnecessarily.
Run git gc only when needed, or use it during off-hours for large repositories.
Using git gc --prune=now without knowing it deletes unreachable objects immediately.
This can remove objects you might still want to recover if you made a mistake recently.
Use --prune=now only when you are sure you no longer need unreachable objects.
Summary
git gc cleans up unnecessary files and optimizes your git repository.
Use git gc --aggressive for a deeper cleanup that takes more time.
Use git gc --prune=now to immediately remove unreachable objects.