You can significantly reduce the size of a Git repository by removing old screenshots using git filter-branch or git rm combined with history rewriting. This process permanently deletes binary files from all commits, ensuring that large assets do not bloat your version control system and improve cloning performance.
Assessing Repository Size and Identifying Targets
Before attempting to rewrite history, it is crucial to understand which files are consuming the most space. Large binary files, such as PNG or JPG screenshots, often accumulate in repositories over time, especially if they were committed by mistake or for documentation purposes that no longer require version tracking. You should identify these files by their extensions, typically.png, .jpg, .jpeg, or .gif.
Run the following command in your terminal to list the largest files in your repository's history. This helps you confirm that screenshots are indeed the primary source of bloat.
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | sed -n 's/^blob //p' | sort -k2 -n | tail -10
This output will show you the largest blobs. If you see image files at the top, you have confirmed the issue. It is also wise to check the current working directory to ensure no active work depends on these specific historical versions. Once identified, you can proceed with cleaning the history. Remember that rewriting history changes commit hashes, so coordinate with your team before forcing updates to shared branches.
Removing Files Using Git Filter Branch
The most reliable built-in method for removing files from all historical commits isgit filter-branch. This command allows you to apply a filter to every commit in your repository, effectively excising specified files from the entire timeline. While newer tools exist, this native Git command requires no external dependencies and works in standard repositories.
To remove all screenshot files from your repository, use the --index-filter option for speed. The following command removes all files matching the pattern *.png and *.jpg from every commit.
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch *.png *.jpg *.jpeg *.gif' \
--prune-empty -- --all
This command instructs Git to run git rm on the index (staging area) for each commit. The --cached flag ensures only tracked files are removed, leaving untracked local copies alone. The --ignore-unmatch flag prevents errors if a commit does not contain any of the specified file types. The --prune-empty flag removes commits that become empty after the removal, keeping the history clean.
After running this, verify that the files are gone from the history by checking out an old commit hash. If the files are missing, the operation was successful. However, the old references still exist in the .git/refs/original directory, which must be cleaned up to reclaim space.
Cleaning Up Reflog and Reclaiming Space
Rewriting history does not immediately delete the old objects; they remain in your local Git database until garbage collected. To permanently free up the disk space, you must first remove the backup references created byfilter-branch. Run the following command to delete these refs.
rm -rf .git/refs/original/
Next, expire the reflog entries. The reflog keeps track of where your HEAD and branch pointers have been, including the old, heavy commits. Clearing it ensures Git knows those old commits are no longer needed.
git reflog expire --expire=now --all
Finally, perform a garbage collection to physically remove the unreachable objects from your disk. This step actually deletes the large screenshot blobs from your local storage.
git gc --prune=now --aggressive
The --aggressive flag takes longer but compresses the pack files more thoroughly, resulting in a smaller repository size. After this completes, your local repository should be significantly lighter.
Pushing Changes to Remote Repositories
Since you have rewritten the history, the commit hashes on your local machine no longer match those on the remote server. Attempting a normalgit push will fail because the remote expects the old history. You must force push the updated history to overwrite the remote branches.
Use the following command to update the main branch. Be cautious, as this will overwrite the remote history for everyone collaborating on the project. Ensure all team members are aware of this change and pull the new history afterward.
git push origin main --force
If you have multiple branches with screenshots, you may need to force push each one individually or use --all to update all local branches that track remote ones. After pushing, verify the remote repository size has decreased. You can also consider configuring a .gitignore file to prevent future screenshots from being committed accidentally.
For teams managing complex merge strategies alongside history cleanup, understanding how to squash merges can help maintain a cleaner narrative. See The Right Way to Squash Merge Master Branches for best practices on maintaining linear history. Additionally, knowing how to properly push to your main branch is essential after any force-push operation. Check How to Git Push to Origin Main: A Tech Support Guide for detailed instructions on handling upstream changes safely.
Frequently Asked Questions
Will removing screenshots delete my current local files?
No, the commands above only affect tracked files in the Git history. Your local working directory remains untouched unless you explicitly run git checkout to restore an older state. Always keep a backup of important data before rewriting history.
Can I recover deleted screenshots after running filter-branch?
Once you run git gc and push the force update, recovery becomes extremely difficult because the objects are physically deleted from the database. If you haven't pushed yet, you can abort the operation by resetting your branch to the original commit hash before the filter-branch command.
Why is my repository still large after cleaning?
If the size hasn't changed, you may have forgotten to run git gc --prune=now or the remote server caches old objects. Some hosting providers require a manual trigger to clear their cache. Also, ensure you aren't storing large files in submodules or lfs without proper configuration.
Is there a safer alternative to filter-branch?
Yes, git rebase -i can remove specific commits, but it is tedious for bulk file removal. Another modern tool is git-filter-repo, which is faster and less error-prone than filter-branch, but it requires separate installation and is not included in standard Git distributions.
How do I prevent screenshots from being committed again?
Add a .gitignore file to your repository root and include patterns like *.png, *.jpg, and screenshots/. This tells Git to ignore these files entirely, preventing them from ever entering the version control system again.