Richard77
Richard77

Reputation: 21641

What's the svn revert equivalent in git?

I'm trying to find the equivalent of svn Revert in Git. In svn, when I rigth-click a file then click revert, that will undo all the local edits. the file goes back to the last commit. I can't find the exact same command in Git. Since I'm new, I don't want to mess-up my work.

Let say I made a commit Init. Then I made some changes. Now I'd like to go back to the Init state.

Thanks for helping

Upvotes: 26

Views: 18252

Answers (3)

John Szakmeister
John Szakmeister

Reputation: 47032

Because of the staging area, it's not quite as simple as an svn revert. Depending on what you've done, and what your goal is, you need to use either git checkout or git reset. You need to be careful with git reset though, as you can re-write history and lose work.

Let's say you have the commit graph:

A <-- B <-- C <-- D

And you're currently at D with some changes. To simply discard all changes (staged or not), you can use git reset --hard HEAD or git reset --hard D. Both will reset the state of your working copy.

If you want the state of your working copy to be identical to A, but not lose commits B and C, then you should use: git checkout A -- . from the top of your working copy. That'll set the state of your working copy to the contents of A. At this point, your working tree is dirty, so you'll need to commit to record the fact that you wanted to go back. The commit graph at this point would be:

A <-- B <-- C <-- D <-- A'

Where A' is a new commit (with a different id) that brings your work back to the equivalent of commit A.

If you want to lose commit B and C, you can use git reset --hard A. This will move your branch pointer back to commit A. You are now re-writing history, so be careful. If you're working with other team members on this branch, you don't want to do this. If it's your own branch, you likely need to use git push -f, where the -f stands for --force, when pushing it to your remote repo. You also need to make sure that you've set push.default to either current or upstream to avoid pushing all matching branches and accidentally rewinding someone's work.

FWIW, I wrote up a blog post about reverting changes in Git several years ago. It's still relevant today. You may find it useful.

Upvotes: 21

Daniel
Daniel

Reputation: 911

As long as the files are not staged I usually use

git checkout -- .

You can also use

git checkout HEAD -- path/to/some/file.txt

to checkout a single file from HEAD, or any other commit

Upvotes: 18

Carl Norum
Carl Norum

Reputation: 224944

git reset --hard Init

Will get your HEAD back to Init. You may want to make a branch or tag first, to save whatever other work you'd done.

Upvotes: 1

Related Questions