Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Git Tips: Revert with a new commit

DZone's Guide to

Git Tips: Revert with a new commit

· DevOps Zone
Free Resource

Download “The DevOps Journey - From Waterfall to Continuous Delivery” to learn learn about the importance of integrating automated testing into the DevOps workflow, brought to you in partnership with Sauce Labs.

Sometimes you want to set the state of your project back to a previous commit, but keep the history of all the preceding changes. You want to make a commit that reverses all the changes between your previous commit and the current HEAD.

First let’s create a new branch, ‘revert-branch’, from the commit we want to revert to. In this example we’re just reverting to the previous commit (I’m assuming that we’re currently in branch ‘master’), but this can be any commit:

git branch revert-branch HEAD^

Next checkout your new branch:

git checkout revert-branch

Now the neat trick: soft reset the HEAD of the new branch to master. A soft reset changes the state of HEAD, but doesn’t affect the working tree or index:

git reset --soft master

Now if we do a git status, we’ll see that the index reports the reverse of the commit(s) that we want to revert. In this case I want to back out of the addition of ‘second.txt’, but this could be a far more complex set of changes:

$ git status

# On branch revert-branch

# Changes to be committed:

#   (use "git reset HEAD <file>..." to unstage)

#

#       deleted:    second.txt

#

Now I can commit this ‘reversal’:

git commit -m "reverted to initial state."
Test and merge revert-branch into master. Nice.

Discover how to optimize your DevOps workflows with our cloud-based automated testing infrastructure, brought to you in partnership with Sauce Labs

Topics:

Published at DZone with permission of Mike Hadlow, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}