I created a new branch, then I created one new commit on this new branch. Now, I want create a new commit that will be before the previous commit. And I don't want to change the previous commit.
How can I do it in a simple way?
First off, you cannot insert a commit in front of another and have the second keep its original SHA. However, the changes applied by the second commit can be unchanged.
I think you have two choices:
git rebase -i
and reorder the commitsThis has the advantage that you can always git rebase --abort
to get back to a clean state where all your commits are available. On the other hand, if your two commits touch the same bit of code, you will be applying your new change to the current state of the code, and then will have to re-write it for the previous state; this might or might not turn out to be complicated.
git-rebase -i
and break
and create a new change before the first onegit rebase -i
. Insert a new line containing just break
to the start of the change listgit rebase --continue
. Your existing commit will be added on top of the current one. There may be conflicts to resolve.This has the advantage that you'll be making your changes when your working directly is in the state you expect it to be.
It has the disadvantage that if there are conflicts in the second commit, you can't just use git rebase --abort
to get back to a safe place as it will lose your new commit. If you did remember to note down the commit SHA of your new change, you can start from step 1 again, and do git cherry-pick THE-SHA
to get your changes back for step 2.