How to Use Git Like a Pro: Branching, Merging & Rebase Explained
Introduction
Git is a distributed version control system used by developers to manage code changes. This tutorial covers three of the most powerful and commonly used features in Git: branching, merging, and rebasing. Understanding how and when to use each will help you work more efficiently, collaborate more effectively, and avoid common pitfalls in version control.
Step 1: Understand Branching
A Git branch is essentially a lightweight movable pointer to a commit. Branches allow you to isolate work without affecting the main codebase.
git branch feature-login
This command creates a new branch called feature-login
based on your current branch.
git checkout feature-login
This switches your working directory to the new branch.
Step 2: Make and Commit Changes
Make some changes to your files, then stage and commit them:
git add .
git commit -m "Add login feature markup"
Now your work is safely recorded in the feature branch without affecting the main branch.
Step 3: Merging Branches
Once your feature is complete, you’ll want to merge it into the main branch (often main
or master
):
git checkout main
git merge feature-login
This applies all the commits from feature-login
onto main
. If there are no conflicts, Git automatically completes the merge. Otherwise, you’ll be prompted to resolve them.
Step 4: Rebasing
Rebasing is an alternative to merging that creates a linear project history. Use it when you want to incorporate changes from one branch into another by rewriting commit history.
git checkout feature-login
git rebase main
This applies your feature branch commits on top of the latest main
branch. If conflicts occur, Git will pause and allow you to fix them manually. After fixing a conflict, use:
git add .
git rebase --continue
Step 5: Push Changes to Remote
Once merged or rebased locally, push your changes to the remote repository to share them:
git push origin main
If you rebased, and previously pushed the feature branch, you’ll need to force push:
git push origin feature-login --force
Use this with caution, as force pushing rewrites history.
Conclusion
Branching, merging, and rebasing are core skills in modern software development with Git. Branching lets you work safely in isolation. Merging helps integrate changes without losing history. Rebasing offers a clean, linear commit timeline. Use each method thoughtfully, and your development workflow will stay organized and efficient.