Rebasing a Git branch onto main moves the branch's own commits so they sit after the current main commit. Use it before review when main has advanced and the feature branch should read as if it started from that newer base.

git rebase main compares the checked-out branch with main, finds commits reachable only from the branch, and replays them in order on top of main. The branch keeps its name, but the replayed commits get new hashes because their parent commit changes.

Run this on local or private branch commits unless the team expects a rewritten shared branch. Start from a clean working tree, and make sure main already points to the target commit before the rebase starts.

Steps to rebase a Git branch onto main:

  1. Open a terminal in the repository and switch to the branch that should move on top of main.
    $ git switch feature/docs
    Switched to branch 'feature/docs'
  2. Confirm the branch has no uncommitted tracked changes.
    $ git status --short

    No output from git status –short means the working tree and index have no tracked changes. Stash or commit unfinished work first if this command prints files. Related: How to stash uncommitted changes in Git

  3. Inspect the current branch layout before rewriting history.
    $ git log --oneline --decorate --graph --all
    * 8c4c2d0 (main) Update main baseline
    | * b39ddf2 (HEAD -> feature/docs) Expand API notes
    | * ac2d465 Add API notes
    |/  
    * b6387f6 Initial notes

    In this example, main has one commit that is not under feature/docs yet. If main tracks a remote branch, fetch or fast-forward it before using it as the rebase target.

  4. Rebase the current branch onto main.
    $ git rebase main
    Rebasing (1/2)
    Rebasing (2/2)
    Successfully rebased and updated refs/heads/feature/docs.

    Rebase rewrites commit IDs on the current branch. If Git stops for conflicts, resolve the files, stage them, and run git rebase --continue; use git rebase --abort to return to the old branch state. Related: How to resolve a Git merge conflict

  5. Verify that main now sits below the feature commits.
    $ git log --oneline --decorate --graph --all
    * 315a62f (HEAD -> feature/docs) Expand API notes
    * e2a00c9 Add API notes
    * 8c4c2d0 (main) Update main baseline
    * b6387f6 Initial notes

    The feature commit hashes changed from ac2d465 and b39ddf2 because Git replayed the commits with main as their new parent.

  6. Confirm the branch is clean after the rebase.
    $ git status --short --branch
    ## feature/docs