Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
2 views
in DevOps and Agile by (29.3k points)

I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:

When I want to revert to a previous commit I use:

git reset --hard HEAD

And Git returns:

HEAD is now at 820f417 micro

How do I then revert the files on my hard drive back to that previous commit?

My next steps were:

git add .

git commit -m "revert"

But none of the files have changed on my hard drive...

What am I doing right/wrong?

1 Answer

+2 votes
by (50.2k points)

If you need to switch temporarily to a committed branch

$git checkout <commit-id>

commit id will be available in

$git log

and it should be the id of the commit that you need to revert. If you need to make commits, go ahead and make a new branch 

$ git checkout -b <old-state> <commit-id> (ie ;- $git checkout -b master <commit-id>)

To go back, you just check out the branch that you were on again. (If you've made changes, when switching branches, you'll have to deal with them as appropriate. You could reset to throw them away, you could commit them to a branch there if you want a branch there.)

HARD DELETE FOR UNPUBLISHED COMMITS

If you need to reset all mess that you have created during revert use

$git reset --hard <commit-id>

Do only if you have committed the work that you need further. Also, you can stash, pop if there is a work to save

This saves the modification, then re-applies that patch after resetting. If you already published the commits then you need to undo the published commits with new commits.

Undoing published commits can be done by using revert command.

$git revert <commit-id>

you can give the reverted commits by giving ranges.

$git revert HEAD~2...HEAD.

Reverting a merge commit

$git revert -m 1 <merge_commit>

 You can get your index and work tree into the desired state, without changing HEAD

$git checkout 0d1d7fc32 .(commit-id)

then finally commit using $ git commit, thus, you can undo published commits.

by (29.3k points)
nice explanation, thanks. git revert HEAD~2 ...HEAD is the best way so I can revert back commits within range.
by (19.4k points)
Similarly, you can revert n number of commits with this command: git revert HEAD~n

Browse Categories

...