0
0
Gitdevops~30 mins

Rebase vs merge mental model in Git - Hands-On Comparison

Choose your learning style9 modes available
Rebase vs Merge Mental Model
📖 Scenario: You are working on a shared project with a friend. Both of you make changes in separate branches. Now, you want to combine your friend's changes into your branch. There are two ways to do this: merge and rebase. Understanding the difference helps keep the project history clean and easy to follow.
🎯 Goal: Learn how to use git merge and git rebase commands to combine changes from one branch into another, and understand the difference in how they affect the project history.
📋 What You'll Learn
Create two branches: main and feature
Add commits to both branches
Use git merge to combine feature into main
Use git rebase to replay feature commits on top of main
Observe the difference in commit history
💡 Why This Matters
🌍 Real World
Developers often work on separate branches and need to combine their work. Choosing between merge and rebase affects how the project history looks and how easy it is to understand changes.
💼 Career
Knowing when and how to use git merge and rebase is essential for collaboration in software teams, making you a better team player and improving code quality.
Progress0 / 4 steps
1
Setup initial repository and branches
Initialize a new git repository. Create a file called file.txt with the text Initial content. Commit this change on the main branch. Then create a new branch called feature.
Git
Need a hint?

Use git init to start the repo. Use echo to create the file. Use git add and git commit to save changes. Use git branch feature to create the branch.

2
Add commits to both branches
Switch to the feature branch. Add a line Feature work to file.txt and commit it with message Feature commit. Then switch back to main branch. Add a line Main work to file.txt and commit it with message Main commit.
Git
Need a hint?

Use git checkout to switch branches. Use >>> to add lines to the file. Commit each change with git commit -m.

3
Merge feature branch into main
On the main branch, run git merge feature to combine the changes from feature branch. This will create a merge commit.
Git
Need a hint?

Make sure you are on main branch, then run git merge feature.

4
Rebase feature branch onto main
Reset the repository to before the merge (for example, by running git reset --hard HEAD~1 on main). Then switch to the feature branch and run git rebase main to replay feature commits on top of main. Finally, switch back to main and merge feature with a fast-forward merge using git merge feature.
Git
Need a hint?

Use git reset --hard HEAD~1 to undo the merge commit. Then rebase feature on main. Finally, merge with fast-forward.