Fixing Merge Conflicts in Git Tutorial

beginner
24 min

Fixing Merge Conflicts in Git Tutorial

Welcome back to CodeYourCraft! Today, we're going to dive into a crucial aspect of Git: fixing merge conflicts. 🎯

What are Merge Conflicts?

Merge conflicts arise when you and your team members are working on the same file and try to merge your changes. Git can't automatically decide which changes to keep, and it needs your help to resolve the issue. 💡

Why do Merge Conflicts occur?

Merge conflicts occur due to differences in lines added, deleted, or modified by different team members in the same file. Let's take an example to understand this better.

Suppose you and your team member are working on a file index.html. If you both modify the same lines of code, Git will not be able to merge the changes automatically, and a merge conflict will occur.

How to identify and resolve merge conflicts?

Step 1: Identifying a merge conflict

When you try to merge a branch with the current one, Git will inform you if there are any merge conflicts.

bash
$ git checkout my-branch $ git merge master Auto-merging index.html CONFLICT (content): Merge conflict in index.html Automatic merge failed; fix conflicts and then commit the result.

Step 2: Resolving the merge conflict

To resolve the conflict, you need to manually edit the file and decide which changes you want to keep. You can do this by opening the conflicted file using the command:

bash
$ git open index.html

You'll see something like this:

html
<<<<<<< HEAD <!-- Original content from the current branch --> <h1>Original Heading</h1> ====== <!-- Content from the branch you're merging in --> <h1>New Heading</h1> >>>>>>> my-branch

Choose the content you want to keep and remove the conflicting sections (<<<<<<<, ======, >>>>>>>). Save the file and exit.

Step 3: Committing the resolved changes

After resolving the conflicts, you need to stage and commit the changes:

bash
$ git add index.html $ git commit -m "Resolved merge conflict in index.html"

Now, the merge conflict is resolved, and the branches are successfully merged.

Pro Tip:

  • Always try to work on separate branches to avoid merge conflicts.
  • Use tools like GitHub's Pull Request feature to review and merge changes more efficiently.

Quiz

Quick Quiz
Question 1 of 1

What happens when you try to merge two branches with conflicting changes?

That's all for today! Stay tuned for more Git tutorials on CodeYourCraft. Happy coding! 📝