Basic Git Series: Understanding Git Rebase

Adam Sturge | Sep 19, 2023 min read

Overview

Git rebase is an alternative to merging that rewrites commit history to create a cleaner, more linear project history. Instead of creating a merge commit, rebasing moves or combines a sequence of commits to a new base commit.

Steps

  1. Update your local main branch:
git checkout main
git pull
  1. Switch to your feature branch:
git checkout feature-branch
  1. Rebase your branch onto the latest main:
git rebase main
  1. If there are conflicts, resolve them:

    • Edit the conflicted files
    • Add the resolved files: git add <filename>
    • Continue the rebase: git rebase --continue
    • (To abort the process: git rebase --abort)
  2. Push your changes (requires force push if the branch is already on remote):

git push --force-with-lease origin feature-branch

Common Issues

  • Conflicts during rebase: Similar to merge conflicts, you’ll need to resolve them manually
  • Lost commits: Rewriting history can cause commits to be lost if not done carefully
  • Force push dangers: Using --force can overwrite others’ changes; use --force-with-lease instead

Additional Notes

  • Golden rule of rebasing: Never rebase branches that others are working on
  • Use interactive rebasing to clean up your commits before sharing:
    git rebase -i HEAD~3  # Rebase the last 3 commits
    
  • Interactive rebase options:
    • pick: Keep the commit as is
    • reword: Edit the commit message
    • squash: Combine with previous commit
    • fixup: Combine with previous commit, discard the message
    • drop: Remove the commit

When to Use Rebase vs. Merge

  • Use rebase when:

    • You want a clean, linear history
    • You’re working on a feature branch that only you use
    • Before submitting a pull request, to incorporate latest changes
  • Use merge when:

    • You want to preserve the complete history
    • You’re working on a shared branch
    • You want to clearly show where a feature branch was integrated