February 25, 2025
O. Wolfson
Version control is essential for modern software development, and Git's branching and merging capabilities are at the heart of effective collaboration. Whether working solo or in a team, understanding how to create, switch, and merge branches properly will streamline development and prevent conflicts.
Branches allow developers to work on features, bug fixes, and experiments independently without interfering with the main codebase. This ensures:
To work with branches effectively, you need to create and switch between them as needed. Here are the essential commands:
sh# Create a new branch named 'feature-branch'
git branch feature-branch
sh# Switch to an existing branch
git checkout feature-branch
# Alternatively, use the modern command
git switch feature-branch
shgit checkout -b feature-branch
# OR
git switch -c feature-branch
Once development on a feature branch is complete, it needs to be merged back into the main branch (often main or develop). This can be done with:
sh# Switch to the main branch
git checkout main
# Merge the feature branch
git merge feature-branch
Sometimes, Git cannot automatically merge changes, resulting in a merge conflict. Git marks the conflicting sections in files like this:
sh<<<<<<< HEAD
Current code in main branch
=======
Code from feature-branch
>>>>>>> feature-branch
To resolve:
Manually edit the file to keep the correct version.
Remove the conflict markers (<<<<<<<, =======, >>>>>>>).
Stage and commit the resolved file:
shgit add conflicted-file.txt
git commit -m "Resolved merge conflict"
A fast-forward merge occurs when the target branch has not diverged from the feature branch:
shgit merge --ff feature-branch
This moves the branch pointer forward, avoiding extra merge commits.
A non-fast-forward (or true) merge creates a new commit even if a direct linear merge is possible:
shgit merge --no-ff feature-branch
This is useful for preserving a clear history of feature work.
Initialize a repository (if not already done):
shgit init my-project
cd my-project
echo "Initial content" > file.txt
git add file.txt
git commit -m "Initial commit"
Create and switch to a feature branch:
shgit switch -c feature-1
echo "Feature 1 changes" >> file.txt
git add file.txt
git commit -m "Add feature 1 changes"
Create and switch to another feature branch:
shgit switch main
git switch -c feature-2
echo "Feature 2 changes" >> file.txt
git add file.txt
git commit -m "Add feature 2 changes"
Merge feature-1 into main:
shgit switch main git merge feature-1
Try merging feature-2 and resolve conflicts:
shgit merge feature-2
If there is a conflict, manually edit file.txt, remove conflict markers, and commit the resolution.
Verify the merged history:
shgit log --oneline --graph --all
By practicing these commands and workflows, you’ll gain confidence in managing branches and resolving merge conflicts efficiently. Happy coding!