How to invert 2 commits in Git
Let's see how to change the order of commits in Git and rewrite commit history
You are currently on a development branch called b1
and you have created 3 commits.
alina
alina git:( b1 ) git log --graph --oneline --all
* 8715c07 (HEAD -> b1) add A2.txt
* 3a49c60 add A3.txt
* 1a49c9d add A1.txt
* 5516221 (origin/main, origin/HEAD, main) Initial commit
alina git:( b1 ) █
Your commit graph looks like this:
Now, you realize that you want to change the order of the last 2 commits, so that add A3.txt
comes before add A2.txt
.
To achieve this, you can use the command git rebase -i <commit-hash>
, where <commit-hash>
is the hash of the commit
before the first commit you want to switch.
In this case, the commit 1a49c9d
is the last commit before the commit(s) you want to modify, so you would run:
alina
alina git:( b1 ) git rebase -i 1a49c9d
alina git:( b1 ) █
This command opens an editor with a list of the commits that will be rebased:
pick 3a49c60 add A3.txt
pick 8715c07 add A2.txt
The order of the commits listed determines the order in which they will be applied. To switch the order of the commits, you simply need to invert the order of the lines:
pick 8715c07 add A2.txt
pick 3a49c60 add A3.txt
After making the necessary changes, the two commits will be rewritten in the desired order:
alina
alina git:( b1 ) git log --graph --oneline --all
* d8cd8e7 (HEAD -> b1) add A3.txt
* 04748fe add A2.txt
* 1a49c9d add A1.txt
* 5516221 (origin/main, origin/HEAD, main) Initial commit
alina git:( b1 ) █
As a result, the new commit graph will look like this:
The commit 1a49c9d
remains the same, but the following two commits have been rewritten.
If the original commits had already been pushed to the remote repository, you would need to perform a git push --force
to rewrite the history…