bashintermediate

Git Repository Cleanup and Maintenance

Commands for cleaning untracked files, pruning refs, optimizing repo size, and maintenance tasks.

bash
# Remove untracked files (dry run first)
git clean -n        # show what would be removed
git clean -f        # actually remove untracked files
git clean -fd       # remove untracked files and directories
git clean -fX       # remove only ignored files
git clean -fx       # remove ignored and untracked

# Prune remote-tracking branches
git fetch --prune
git remote prune origin

# Delete merged branches
git branch --merged main | grep -v 'main' | xargs git branch -d

# Garbage collection and optimization
git gc
git gc --aggressive --prune=now

# Check repo size
git count-objects -vH

# Find large files in history
git rev-list --objects --all | \
  git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | \
  sed -n 's/^blob //p' | sort -rnk2 | head -10

# Verify repository integrity
git fsck --full

# Remove file from entire history
# git filter-branch --force --index-filter \
#   'git rm --cached --ignore-unmatch path/to/large-file' HEAD

# Scheduled maintenance (Git 2.30+)
git maintenance start  # enables background maintenance
git maintenance run    # manual run

Use Cases

  • Reducing repository size and improving performance
  • Cleaning up after feature branch workflow
  • Repository health checks and diagnostics

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.