DEV Community

Jasper Hu
Jasper Hu

Posted on

๐Ÿ”ย Git Rebase Tutorial

๐Ÿ” Git Rebase: Rebasing a Feature Branch onto a Parent Branch

This guide walks you through the steps of rebasing a feature branch onto its parent (target) branch using Git.

โœ… Steps to Rebase a Feature Branch

  1. Fetch the latest changes from the remote repo

    git fetch origin
    
  2. Check out the parent branch and pull the latest updates

    Replace main with your actual parent branch name.

    git checkout main
    git pull origin main
    

    Why do we need git pull origin main after git fetch origin?

    โ€” Short answer:

    git fetch origin only downloads the latest updates from the remote (like origin/main), but it does not update your local main branch.

    To update your local main, you must explicitly pull or reset it

  3. Switch to your feature branch

    git checkout my-feature-branch
    
  4. Start rebasing your feature branch onto the updated parent branch

    git rebase main
    
  5. Resolve conflicts if they occur

    • Git will pause and prompt you to resolve merge conflicts.
    • Open the conflicted files and resolve them manually.
    • Then mark them as resolved:

      git add <resolved-file_1> <resolved-file_2> ...
      

    Why do I need to git add after i staged the changes in GUI when resolving conflicts?
    โ€” Short Answer:

    Staging in the GUI may only visually mark the changes, but Git still requires an explicit git add (or the GUI equivalent) to tell Git: โ€œI have resolved this conflict.โ€

  6. Continue the rebase process

    git rebase --continue
    

    If you're using the terminal and see the editor open for commit messages, type :wq to save and exit (if using Vim).

  7. Force push your updated feature branch to the remote repository

    This is required because the commit history has changed.

    git push origin my-feature-branch --force
    

    This will overwrite the old version of the feature branch on the remote.

  8. Optional: Fetch again (not usually needed)

    • If your Git client shows a message about unsynced commits, it should go away after the force push.
    • You don't need to fetch again unless you're unsure if the rebase was completed.

โœ… After these steps, your feature branch will be rebased on top of the latest parent branch, with a clean commit history.

Let me know if you want me to tailor it to a specific project structure (e.g., API vs. frontend branches).

โ“ Common Questions (Remains to be answered later)

  1. Why do we need git pull origin main after git fetch origin?
  2. Do I need to fetch again after the rebase and force push?
  3. Why does Git GUI show uncommitted changes after a rebase, even if I already committed everything?
  4. Whatโ€™s the general approach to resolving merge conflicts during a rebase?

Top comments (0)