Search code examples
gitgit-rebase

Reorder local commits


I want to reorder git commits at my local branch, currently, my brach looks like this.

x-x-x-x-x-x-x-0-1-2-3

now I want to change the order to below

x-x-x-x-x-x-x-0-2-1-3 how is it possible to do with git?


Solution

  • You may use an interactive rebase:

    git rebase -i HEAD~4
    

    This will bring up an editor looking something like the following:

    pick 39vm3ie commit 0
    pick md93ndj commit 1
    pick 25sf3kd commit 2
    pick 03kdoj3 commit 3
    

    Note that the last four commits appear in order from oldest at the top, to newest at the bottom. Since you want to change the order of the 1 and 2 commits, you may rearrange them as follows:

    pick 39vm3ie commit 0
    pick 25sf3kd commit 2
    pick md93ndj commit 1
    pick 03kdoj3 commit 3
    

    Now just save the editor and close, which will initiate the rebase. You may have to resolve some merge conflicts along the way, as rebasing rewrites history. Note that because you are rewriting history, this option should probably be avoided on public branches which may already be checked out by other developer.