1

I made 3 'git commit' but I have not done a 'git push'.

1. commit 1
2. commit 2
   touches fileA
   touches fileB
   touches fileC
3. commit 3

So How can I

  1. roll back changes I made in file b for commit 2? (I can't do a 'git checkout -- fileB' anymore since I already 'git commit', how can i roll back my changes?
  2. make changes in fileC and make it like part of commit 2? I think I can go and change the file now and then run a 'git rebase -i HEAD~2' Correct?

4 Answers 4

5

This should work:

1. git rebase -i HEAD~2
2. in your editor, select the following:

edit 9b86592 commit 2
pick f3907cb commit 3

3. at this point roll back the changes you made in fileB, for example with
   `git checkout <version_you_want>` or by manually editing the file
4. make the changes in fileC you want to be part of commit 2
5. `git add fileB fileC`
6. `git commit --amend`
7. `git rebase --continue`

You may need to resolve merging issues if there are conflicts when git tries to apply commit 3. After you resolve those, run git rebase --continue again.

Sign up to request clarification or add additional context in comments.

Comments

2

Use git rebase -i HEAD~2 and edit the second commit.

Comments

0

Assuming that you are on branch master and have a clean tree:

# checkout incorrect commit
git checkout <sha1_of_commit2>

# revert the changes to fileB by checking out the parent version
git checkout HEAD^ -- fileB

# make an amended commit
git commit --amend

# go back to master
git checkout master

# transplant the changes since the bad commit onto the amended commit
git rebase --onto HEAD@{1} <sha1_of_commit2>

1 Comment

@kaizer.se: Some people find it easier, personally I find it takes longer to explain as you have to describe the rebase -i command and how to edit the interactive rebase commit list in addition to the other important steps. Describing how to do things 'manually' is simpler. Most of the answers suggesting rebase -i either have more steps than my recipe, or more complex steps or more implied steps that aren't explicitly described.
0

This is how I would do it.

Checkout the old version of fileB and commit it

git checkout HEAD~3 -- fileB
git commit -m"fix fileB" fileB

Now rebase to squash in your fix with the old commit

git rebase -i HEAD~3

now move your most recent commit "fix fileB" to be after commit 2, and change the "pick" instruction to "squash", joining the commit changing fileB with the commit resetting it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.