Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right way to discard changes in Git

I've seen many different approaches for discarding changes / reverting to a previous commit using Git. I usually can figure out which works for my situation, but in the process I've gotten quite confused by the different approaches. Most recently I was trying to undo some file renames and no matter how hard I tried to git checkout the old versions of the files I still couldn't get my old files back.

I'm looking for clarification on which approach to use and why. Here is my understanding of a few approaches. I realize that the answer may be very contextual, but I'd like to try and sort out which contexts require which approaches.


1)git checkout -- .

  • Used to checkout the latest version of files, will overwrite old files but will not affect deleted, renamed, or new files.

2)git stash save --keep-index followed by git stash drop

  • Stashes uncommitted files, then drops them entirely. Good approach if you have committed changes you want to keep and uncommitted/unstaged changes you want to discard.

3)git reset --hard

  • Wipes out everything since the last commit, including file renames, deletions, and additions.

This is my current understanding of my options. Are there any changes you would make to my explanations? I'm also unsure when I would use a git revert in lieu of the above commands.

Source posts:

  • Can't seem to discard changes in Git
  • How do I discard unstaged changes in Git?
  • GIT Discard any changes I've made to a branch
like image 685
Kyle Clegg Avatar asked Aug 14 '12 18:08

Kyle Clegg


1 Answers

git stash -u

is the preferred way. Don't drop. They won't get pushed. In case you did zap something you discovered was important, you can get them back.

Your other choices are destructive.

Revert is adding a new commit to the history that applies the opposite of a patch that a commit has introduced. Your choices here are for what you want to do with changes in your worktree that are not yet part of history. Revert is for committed changes that are part of history.

like image 134
Adam Dymitruk Avatar answered Oct 15 '22 15:10

Adam Dymitruk