Daniel
Daniel

Reputation: 12026

Correct previous commit before commiting new changes

I have a simple question, but I couldn't find a duplicate here.

I committed changes (commit 1) to a wip branch and continued on with the development. Now I want to commit new changes (commit 2), but I noticed that commit 1 had a mistake.

How can I save my changes (relative to commit 2) without commiting them, go back to commit 1 and fix it, then bring back those changes and execute commit 2?

Upvotes: 1

Views: 67

Answers (3)

Jagrati
Jagrati

Reputation: 12222

From your question, I have an understanding that you want to add more changes to commit 1.

git stash the changes that you did for commit-2 Then amend the previous commit.

For that You should use git commit --amend. It is described here:

https://www.atlassian.com/git/tutorials/rewriting-history/

Then You can apply the stashed changes using git stash apply

And commit the changes in commit -2

Upvotes: 0

Useless
Useless

Reputation: 67733

Either:

  1. stash your working state and fix commit 1 with commit --amend, or
  2. just commit you changes in the natural order and rebase afterwards. This will give something like

    commit1 -> commit2 -> commit1fix <HEAD
    

    and running rebase -i HEAD~3, you can reorder the commits like so:

    pick aaaa commit1
    fixup cccc commit1fix
    pick bbbb commit2
    

Upvotes: 1

Maroun
Maroun

Reputation: 95958

You can use git stash:

Often, when you’ve been working on part of your project, things are in a messy state and you want to switch branches for a bit to work on something else. The problem is, you don’t want to do a commit of half-done work just so you can get back to this point later. The answer to this issue is the git stash command.

What you should do:

git stash
<checkout other branch>
<commit changes>
<checkout first branch>
git stash pop

Upvotes: 1

Related Questions