In addition to Matthieu Moy's accepted answer, I found this obvious but surprisingly good practice we can follow to prevent such "checkout" accidents from happening again.
"Here's another crazy idea: don't run 'git checkout ...' on a dirty work tree. Problem solved."
This(1) stuck out to me the most that I stopped ever since using git checkout .
to discard any unstaged/uncommitted changes. I now use the command which was made to be more suitable for this: git reset
.
git reset
to unstage changes and git reset --hard
when you're absolutely positively sure you want to discard your changes permanently. git stash
is also your friend, doesn't hurt to stash your changes before you discard them.
Making these two a habit and using git checkout
only for switching between branches (mostly) worked really well for me.
Update: A year later, I've adopted and have been using for quite some time now two new practices which may be of help. I've replaced git reset
with the newer git restore
. I combine it with a "are you sure?" confirmation function in bash(2) for extra caution. confirm && git restore .
is my go-to command now for removing all unstaged changes.
The second is the -p, --patch
option for checkout
(it's there for many other commands like add
which is really useful). It lets you interactively select hunks of code with a confirmation. Thus, git checkout -p
is way safer now if you want to just remove some changes and it doesn't affect staged changes by default.
(1) Relevant part of a comment made by fr0sty on May 13, 2010 in a debate on Hacker News. I got this from the answer by VonC for "Get back the changes after accidental checkout?"
(2) See how to make a general purpose confirm function for use with important commands at the answer for "In Bash, how to add 'Are you sure [Y/n]' to any command or alias?"