How to Rebase Git Branch

There are several Git rebase flows. In this snippet, we are going to show you how to rebase your branch. Here are the steps to follow:

1. Run Git Fetch

You should receive the latest changes from a remote git server. Thus the first step is running git fetch.

git fetch

2. Run Git Rebase

The second step is running git rebase. Rebase is a Git command which is used to integrate changes from one branch into another. The following command rebase the current branch from master (or choose any other branch like develop)

git rebase origin/master

In case of git rebase conflict resolve them, add your changes by running git add, and then continue git rebase, like this:

git rebase --continue

Do not run git commit after git add

Run git rebase --abort to cancel the rebase.

3. Run Git Push

The final step is the git push (forced). This command uploads local repository content to a remote repository. See the code below to run the git push.

git push origin HEAD -f

Git Rebase vs Merge

The main advantage of the rebase command is that it makes the git log look clean. It keeps the commit history out of the branch, contrary to the merge command, which is its alternative. While, for individuals, rebasing is not recommended in the case of feature branch because when you share it with other developers, the process may create conflicting repositories.

Use git merge branch, if you want to see the history completely the same as it happened. Merge keeps the history whereas rebase rewrites it.

Git fetch

The git fetch command downloads commits, files, and refs from a remote repository into the local repository. Git fetch updates your remote-tracking branches.

Git fetch allows you to see the progress of the central history, not forcing you to merge the changes into your repository. It does not affect your local work process.

Do not confuse the fetch command with the "pull" as here it will merge the changes with your branch.

The git pull command is used to fetch and download content from a remote repository and update the local repository to match that content.

Git Force Push

Git push is the opposite of git fetch, as fetching imports commits to local branches, pushing exports them to remote branches. Use -f to force the push.

The difference between git force push and usual push is that you only force a push when you need to replace the remote history by your local history.

Do you find this helpful?

Related articles