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
-
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
-
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 thegit commit
command after thegit 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 thegit rebase --abort
command. -
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.
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