Overview
Merging combines changes from different branches. It’s how you integrate feature branches back into your main codebase.
Steps
- Check out the branch you want to merge into (usually main/master):
git checkout main
- Make sure your branch is up-to-date:
git pull
- Merge the feature branch:
git merge feature-branch
- Push the merged changes:
git push
Common Issues
-
Merge conflicts: When Git can’t automatically combine changes, you’ll need to resolve conflicts manually:
- Open the conflicted files (they’ll have special markers showing conflicts)
- Edit the files to resolve conflicts
- Save the files
git add
the resolved files- Continue the merge with
git merge --continue
-
Accidental merge: If you merge by mistake, you can abort before committing:
git merge --abort
Additional Notes
- For a cleaner commit history, consider using
git rebase
instead of merge for some situations - Always verify the changes after merging to ensure everything works
- For complex features, consider using a Pull Request workflow instead of direct merges
- The
--no-ff
flag creates a merge commit even for fast-forward merges:git merge --no-ff feature-branch
Merging on GitHub
You can also merge branches directly on GitHub:
- Navigate to the repository on GitHub
- Go to the “Pull requests” tab
- Open the pull request you want to merge
- If all checks have passed and reviews are approved, click the “Merge pull request” button
- You’ll see different merge options:
- Create a merge commit - Preserves all commits from the branch
- Squash and merge - Combines all changes into one commit
- Rebase and merge - Adds commits individually without a merge commit
- Choose your preferred method and click the confirmation button
- Optionally delete the branch after merging
This approach is often preferred as it provides a clean interface for code reviews and discussions before merging.