Why You Should Use git pull –rebase Instead of git pull

Git pull

When working with Git, you may encounter a situation where your push is rejected because someone else has pushed their changes before you. This tutorial explains how to handle this situation properly using git pull –rebase instead of a regular git pull, ensuring a clean commit history. 

Step 1: Understanding the Problem 

You and another developer (let’s call them John) are working on the same branch. Both of you start from the same commit, make local changes, and commit them. However, John pushes his changes first. When you attempt to push your changes, Git rejects your push because the remote branch is ahead of your local branch. 

Step 2: Why git pull Causes Issues 

A common approach to fixing this issue is running: 

git pull

However, this creates a merge commit, which combines both your commit and John’s commit into a new commit. Over time, repeated merge commits clutter the Git history, making it difficult to track specific changes. 

Step 3: The Better Approach – git pull –rebase 

Instead of merging, we can rebase our commits onto the latest remote branch: 

git pull --rebase

What Happens During Rebase? 

  1. Your local commit is temporarily set aside. 
  1. Git pulls the latest changes from the remote branch. 
  1. Your commit is reapplied on top of the latest remote changes, maintaining a linear history. 

Step 4: Handling Merge Conflicts During Rebase 

If there are conflicting changes between your commit and John’s commit, Git will pause and prompt you to resolve them manually. 

  • Use git status to see the conflicting files. 
  • Edit the files to resolve conflicts. 
  • Once resolved, run:
    git rebase --continue 
     

If you want to abort the rebase and return to the previous state, run: 

git rebase --abort

This restores your branch to its state before the rebase attempt. 

Step 5: Pushing Your Rebased Commit 

Once the rebase is successful, you can push your changes: 

git push --force-with-lease

The –force-with-lease flag ensures you don’t accidentally overwrite new remote changes. 

Step 6: Creating a Shortcut Alias 

Since git pull –rebase is long to type, you can create a shortcut alias: 

git config --global alias.pr "pull --rebase"

Now, you can simply run: 

git pr

Summary 

  1. Avoid git pull because it creates unnecessary merge commits. 
  1. Use git pull –rebase to maintain a clean history. 
  1. Handle conflicts by resolving them and continuing the rebase. 
  1. Use git rebase –abort if something goes wrong. 
  1. Push changes using git push –force-with-lease. 
  1. Set up an alias to simplify the process. 

By following this approach, your Git history remains linear and easy to read, improving collaboration and code maintenance.