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: git checkout feature-branch 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: 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: Skip a Commit
If you encounter a problematic commit that you want to skip, use: Abort a Rebase
To cancel the rebase and return to the original state, use: 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: git rebase --onto newbase oldbase feature-branch Example
Fixing Mistakes in Commit Messages: Use interactive rebase to reword commit messages that need correction: 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: 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: git checkout feature-branch By mastering these Git rebase commands, you can maintain a clean and linear commit history, making your project history easier to read and manage.