Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I roll back 1 file change in my previous commit

Tags:

git

I have made 2 commits (And I have not pushed) in git, where 'Commit 2' is the most recent one':

 git log -2
commit 791962d776f66253d656586b097b2677eaa983d1
Author: michael <michael@michael-laptop.(none)>
Date:   Tue Jun 29 23:20:58 2010 -0700

    Commit 2

commit b743075e81f6fe25fe48ddbef2b5e7cc06623533
Author: michael <michael@michael-laptop.(none)>
Date:   Tue Feb 16 23:09:53 2010 -0800

    Commit 1

And in my commit 1 b743075e81f6fe25fe48ddbef2b5e7cc06623533, I touched/changed a number of files:

   dir1/file1.cpp
   dir1/file1.h
   dir1/file2.cpp
   dir1/file2.h

My questions is, how can I roll back my changes that I made to dir1/file2.cpp, dir1/file2.h of commit 1? And keep everything else the same?

Thank you.

like image 944
michael Avatar asked Jun 30 '10 06:06

michael


People also ask

Can we undo changes after commit?

The git revert command is a forward-moving undo operation that offers a safe method of undoing changes. Instead of deleting or orphaning commits in the commit history, a revert will create a new commit that inverses the changes specified.

How do I revert to a previous version of a file in git?

To move HEAD around in your own Git timeline, use the git checkout command. There are two ways to use the git checkout command. A common use is to restore a file from a previous commit, and you can also rewind your entire tape reel and go in an entirely different direction.


1 Answers

The simplest solution would be, from your latest commit (HEAD) to:

  • checkout those two files at the older version,
  • add them,
  • and then commit.
    git checkout b743075e81 -- dir1/file2.cpp
    git checkout b743075e81 -- dir1/file2.h
    git add dir1/file2.cpp # only if you made additional changes
    git add dir1/file2.h   # only if you made additional changes
    git commit -m "revert dir1/file2.cpp and dir1/file2.h"

As Chris Johnsen mentions in the comments:

git checkout with pathspecs updates the index (like git reset with pathspecs) and the working tree, so git add is not needed unless additional changes are made after the checkout.

like image 55
VonC Avatar answered Sep 18 '22 00:09

VonC