Best Practices for Resolving Git Merge Conflicts
Q: How do you handle merge conflicts in Git, and can you give an example of when you had to resolve one?
- Git
- Junior level question
Explore all the latest Git interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Git interview for FREE!
When you merge changes from one branch into another, Git may detect conflicts between the changes made on the two branches. A merge conflict occurs when the same file or code block is modified in different ways on both branches. Resolving merge conflicts is an essential skill for any developer working with Git.
Here are the steps to handle merge conflicts in Git:
1. Identify the conflicted file(s): When you attempt to merge changes from one branch into another, Git will display an error message indicating which file(s) have conflicts. You can use the command "git status" to see which files have conflicts.
2. Open the conflicted file: Open the file(s) that have conflicts using a code editor or text editor. The conflicted parts will be marked with Git conflict markers "<<<<<<<", "=======", and ">>>>>>>". These markers indicate the conflicting changes made on each branch.
3. Resolve the conflicts: Edit the conflicted parts of the file(s) to resolve the conflicts. You'll need to decide which changes to keep and which to discard. Once you've resolved the conflicts, remove the Git conflict markers from the file(s).
4. Add and commit changes: After resolving the conflicts, stage the conflicted file(s) using the "git add" command and then commit the changes using the "git commit" command.
Here's an example of when you might encounter a merge conflict:
Let's say you're working on a project with a colleague. You both make changes to the same file on separate branches. Your colleague pushes their changes to the remote repository first and then you try to merge your changes into their branch. Git detects a conflict between your changes and your colleague's changes to the same file. You'll need to resolve the conflict by manually editing the file to combine both sets of changes or decide which changes to keep and which to discard. Once you've resolved the conflict, you can commit the changes and push them to the remote repository.


