Skip to main content
All posts

Basic Git Series: Merging Branches in Git

A quick guide on how to merge branches in Git

Overview

Merging combines changes from different branches. It's how you integrate feature branches back into your main codebase.

Steps

  1. Check out the branch you want to merge into (usually main/master):
git checkout main
  1. Make sure your branch is up-to-date:
git pull
  1. Merge the feature branch:
git merge feature-branch
  1. Push the merged changes:
git push

Common Issues

  • Merge conflicts: When Git can't automatically combine changes, you'll need to resolve conflicts manually:

    1. Open the conflicted files (they'll have special markers showing conflicts)
    2. Edit the files to resolve conflicts
    3. Save the files
    4. git add the resolved files
    5. 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:

  1. Navigate to the repository on GitHub
  2. Go to the "Pull requests" tab
  3. Open the pull request you want to merge
  4. If all checks have passed and reviews are approved, click the "Merge pull request" button
  5. 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
  6. Choose your preferred method and click the confirmation button
  7. Optionally delete the branch after merging

This approach is often preferred as it provides a clean interface for code reviews and discussions before merging.