How to Rebase Git Branch

John Wachira Feb 02, 2024
How to Rebase Git Branch

This tutorial covers the various steps you can take to rebase your local branch to a remote master branch using the git fetch, git rebase, and git push commands.

Rebase Local Branch to a Remote Master Branch in Git

  1. Fetch changes

    We use the git fetch command to get all the changes from our remote repository.

    pc@JOHN MINGW64 ~/Git (Branch1)
    $ git fetch
    remote: Enumerating objects: 3, done.
    remote: Counting objects: 100% (3/3), done.
    remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
    Unpacking objects: 100% (3/3), 610 bytes | 3.00 KiB/s, done.
    From https://github.com/Wachira11ke/Delftscopetech
     * [new branch]      main       -> origin/main
    
  1. Make changes

    We run the git rebase command to integrate changes to our branch. The example below will rebase our current branch from the main branch.

    pc@JOHN MINGW64 ~/Git (main)
    $ git rebase main
    Current branch main is up to date.
    

    When conflicts occur, use the git add . command to resolve them. Do not run the git commit command after the git add . command.

    After resolving the conflicts, use git rebase --continue to finish the process. If you want to abort the process after solving the conflicts, use the git rebase --abort command.

  2. Push changes to the remote repository

    To upload the content in your local repository, use the git push -f command as illustrated below.

    git push main HEAD -f
    

    The -f will overwrite any changes made by other developers in the remote repository.

    Below is a safer method to push changes to a remote repository.

    git push --force-with-lease main HEAD
    

    This command will not overwrite the changes made by other developers in the remote repository.

    Rebasing and merging are used to integrate changes from one branch into another. Rebasing is the process of updating a feature branch without disturbing the branch history, allowing for a cleaner commit history.

    It’s the opposite of git merge, which can create conflicting branches when shared with others.

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git Rebase