Skip to content
Advanced Git Techniques

Git Rebase commands

Git Rebase

Git rebase is a powerful feature that allows you to move or combine a sequence of commits to a new base commit. Here are some essential Git rebase commands and how to use them effectively.

Basic Rebase

Rebasing a Branch

To rebase your current branch onto another branch, use the following command:
Code
git checkout feature-branch
git rebase main
This command replays the commits from your feature branch onto the latest commit in the main branch, resulting in a linear commit history.

Interactive Rebase

Rebase Interactively

Interactive rebase allows you to modify the commit history by editing, reordering, or squashing commits. Use the following command to start an interactive rebase:
Code
git rebase -i main
You will see a list of commits that you can pick, reword, squash, or edit. Save and close the editor to apply the changes.

Steps in Interactive Rebase

Pick: This keeps the commit as it is.
Reword: This allows you to change the commit message.
Squash: This combines the commit with the previous one.
Edit: This allows you to make changes to the commit.
After editing the list, save and close the editor. Git will replay the commits according to your instructions.

Continuing and Aborting Rebase

Continue After Conflict Resolution

If conflicts occur during a rebase, Git will pause and allow you to resolve them. Once resolved, add the resolved files and continue the rebase:
Code
git add <file>
git rebase --continue

Skip a Commit

If you encounter a problematic commit that you want to skip, use:
Code
git rebase --skip

Abort a Rebase

To cancel the rebase and return to the original state, use:
Code
git rebase --abort

Advanced Rebase Commands

You can specify a different base for your commits using the --onto option. This is useful when you need to rebase onto a branch other than the current branch's base:
Code
git rebase --onto newbase oldbase feature-branch

Example

Fixing Mistakes in Commit Messages: Use interactive rebase to reword commit messages that need correction:
Code
git rebase -i main
Change pick to reword for the commits you want to edit.
Combining Commits: If you want to combine multiple commits into one, use the squash option during interactive rebase:
Code
git rebase -i main
Change pick to squash for the commits you want to combine.
Rebasing a Feature Branch: Regularly rebase your feature branch to keep it up-to-date with the main branch:
Code
git checkout feature-branch
git rebase main
By mastering these Git rebase commands, you can maintain a clean and linear commit history, making your project history easier to read and manage.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.