Rebasing a branch in Git is a way to move the entirety of a branch to another point in the tree. The simplest example is moving a branch further up in the tree. Say we have a branch that diverged from the master branch at point A:
/o-----o---o--o-----o--------- branch
--o-o--A--o---o---o---o----o--o-o-o--- master
When you rebase you can move it like this:
/o-----o---o--o-----o------ branch
--o-o--A--o---o---o---o----o--o-o-o master
To rebase, make sure you have all the commits you want in the rebase in your master branch. Check out the branch you want to rebase and type `git rebase master` (where master is the branch you want to rebase on).
It is also possible to rebase on a different branch, so that for example a branch that was based on another branch (let's call it feature) is rebased on master:
/---o-o branch
/---o-o-o-o---o--o------ feature
----o--o-o-A----o---o--o-o-o--o--o- master
After `git rebase master branch` or `git rebase master` when you have checked out the branch, you'll get:
/---o-o-o-o---o--o------ feature
----o--o-o-A----o---o--o-o-o--o--o- master
\---o-o branch
### Git rebase interactive in the console
To use `git rebase` in the console with a list of commits you can choose, edit or drop in the rebase:
- Enter `git rebase -i HEAD~5` with the last number being any number of commits from the most recent backwards you want to review.
- In vim, press `esc`, then `i` to start editing the test.
- On the left hand side you can overwrite the `pick` with one of the commands below. If you want to squash a commit into a previous one and discard the commit message, enter `f` in the place of the `pick` of the commit.
```
pick 452b159 <messageforthiscommit>
pick 7fd4192 <messageforthiscommit>
pick c1af3e5 <messageforthiscommit>
pick 5f5e8d3 <messageforthiscommit>
pick 5186a9f <messageforthiscommit>
# Rebase 0617e63..5186a9f onto 0617e63 (30 commands)
- If it rebases successfully then you need to force push your changes with `git push -f` to add the rebased version to your github repo.
- If there is a merge conflict, there are a number of ways to fix this, including following the suggestions in [this guide](https://help.github.com/enterprise/2.11/user/articles/resolving-a-merge-conflict-using-the-command-line/). One way is to open the files in a text editor and delete the parts of the code you do not want. Then use `git add <file name>` followed by `git rebase --continue`. You can skip over the conflicted commit by entering `git rebase --skip`, exit the git rebase by entering `git rebase --abort` in your console.
Git Rebase is a very powerful feature. That being said, it is **risky** as well if it is not used in the right way.
Git rebase alters the commit history. So use it with care. If Rebasing is done in the remote repository, then it can create a lot of issues when other developers try to pull the latest code changes from the remote repository.
As much as possible try using Git Rebase only to rebase a local git repository.