0
0
GitHow-ToBeginner · 3 min read

How to Use git gc: Clean and Optimize Your Git Repository

Use git gc to clean up unnecessary files and optimize your Git repository by compressing file history and removing unreachable objects. Running git gc helps keep your repository efficient and fast.
📐

Syntax

The basic syntax of git gc is simple and can be extended with options:

  • git gc: Runs garbage collection with default settings.
  • git gc --aggressive: Performs a more thorough cleanup but takes longer.
  • git gc --prune=now: Removes all unreachable objects immediately.
bash
git gc [--aggressive] [--prune=<date>]
💻

Example

This example shows how to run git gc to clean and optimize your repository:

bash
git gc

# Output example:
# Counting objects: 1000, done.
# Compressing objects: 100% (800/800), done.
# Writing objects: 100% (1000/1000), done.
# Total 1000 (delta 200), reused 0 (delta 0)
# Removing unreachable objects: 50, done.
Output
Counting objects: 1000, done. Compressing objects: 100% (800/800), done. Writing objects: 100% (1000/1000), done. Total 1000 (delta 200), reused 0 (delta 0) Removing unreachable objects: 50, done.
⚠️

Common Pitfalls

Common mistakes when using git gc include:

  • Running git gc --aggressive too often, which can slow down your workflow because it takes more time.
  • Not understanding that git gc may lock the repository temporarily, so avoid running it during active pushes or pulls.
  • Using git gc --prune=now without caution, which can delete objects that might still be needed if you have unpushed commits.
bash
Wrong:
git gc --aggressive

# Run only when necessary to avoid slowdowns.

Right:
git gc

# Use default for regular cleanup.
📊

Quick Reference

OptionDescription
git gcRun garbage collection with default settings
git gc --aggressivePerform a thorough cleanup, slower but more compact
git gc --prune=Remove unreachable objects older than the given date
git gc --prune=nowRemove all unreachable objects immediately

Key Takeaways

Run git gc regularly to keep your repository clean and efficient.
Use --aggressive only when you need deeper cleanup, as it takes more time.
Avoid running git gc during active repository operations to prevent locking issues.
Be cautious with --prune=now to not delete needed objects prematurely.