Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git stash clear and drop are not really clearing the changes

Tags:

git

git-stash

Have you ever tried these steps with git stash?

touch file1
git add file1
git stash
cat .git/refs/stash # ==> copy the content, which is the latest stashed <sha_1>
git stash clear # ==> we expect that git forget everything about that changes
git stash apply <sha_1>

As you can see, git somehow still knows about my stashed changes!
Is there anyway to remove the changes permanently? Is this a bug?

like image 340
Amin Avatar asked Aug 31 '25 17:08

Amin


1 Answers

When you use git stash, the changes are stored as objects within the Git object database (much like commits), which is how they can be reapplied later. The stash reference is merely a pointer to these objects. When you clear the stash using git stash clear, the reference is removed but the objects are not immediately deleted. They will eventually be garbage collected when Git performs its periodic housekeeping, but until then they can still be accessed directly if you know their SHA-1 hash, the documentation is clear about that:

git clear

Remove all the stash entries. Note that those entries will then be subject to pruning, and may be impossible to recover [...]

This is not a bug but a feature of Git. Git is designed to be very careful about not losing data. Even when you think you've deleted something (like a commit, a branch, or a stash), Git often still keeps it around just in case you made a mistake. These "deleted" items can often be recovered until Git's garbage collection process eventually cleans them up.

If you want to manually trigger Git's garbage collection process, you can do so with the git gc command. This will clean up unreachable or "orphaned" objects in the database. Be aware, though, that this can be a resource-intensive process if you have a large repository.

Here's how to use it:

git gc --prune=now

The --prune=now option tells Git to prune all orphaned objects immediately. Without this, Git will only prune objects that are older than two weeks by default.

Please remember that once the garbage collection process removes these objects, they are gone permanently and cannot be recovered. So, only use this if you're certain that you won't need to recover any of these orphaned objects.

like image 102
Marcin Kłopotek Avatar answered Sep 02 '25 11:09

Marcin Kłopotek