git-trash - Get Rid of Junk, Git Style

First I have to admit that this tip is not mine. It's been going around in the IRC, and I also saw a similar thing in Github.

When people want to get rid of files floating around in their working directories, there are several options:

I most often find myself wanting to just throw away all files, and reset the working directory to the HEAD state. I also want the reset to be safe, meaning that I can regret it if I want to. This does not hold true for the options mentioned above.

A very cool solution is to just add the following alias to your git configuration (either local or global):

git config alias.trash "!git add -A && git commit -m 'trash' && git reset --hard HEAD^"

Now to get rid of modified files, you can just execute

git trash

and this will create a temporary commit with all modified content (tracked and untracked), and then discard it. If you regret it, the commit will remain in the reflog for a while longer (two weeks by default) so that you can retrieve it on emergencies.

UPDATE (2016-02-27) - moved to use git add -A instead of git add . - thanks Joachim Fenkes for pointing it out for me.


blog comments powered by Disqus