When two people edit the same line of code in a file and try to merge those changes, Git gets confused about which version to keep. This is known as a conflict. Don’t worry; resolving conflicts is a skill you can master!
Imagine you and a colleague are both working on a project called awesome-app
, and both of you modify the same line in a file called index.html
.
Here’s how you can resolve a conflict step-by-step using Git commands:
To see a conflict in action, let’s set up the scenario:
## Clone the repository
git clone https://github.com/yourusername/awesome-app.git
cd awesome-app
## Create a new branch for your changes
git checkout -b feature-a
## Modify index.html
echo '<h1>Welcome to Awesome App - Feature A</h1>' > index.html
## Stage and commit your changes
git add index.html
git commit -m 'Added welcome message for Feature A'
## Switch to the main branch
git checkout main
## Create a new branch for your colleague's changes
git checkout -b feature-b
## Modify index.html differently
echo '<h1>Welcome to Awesome App - Feature B</h1>' > index.html
## Stage and commit those changes
git add index.html
git commit -m 'Added welcome message for Feature B'
## Switch back to the main branch
git checkout main
## Merge both feature branches
git merge feature-a
When you try to merge feature-b
into main
, you’ll get a conflict message:
## Attempt to merge
git merge feature-b
## Output:
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.
To see which files have conflicts, run:
git status
Open index.html
in your text editor. You will see something like this:
<<<<<<< HEAD
<h1>Welcome to Awesome App - Feature A</h1>
=======
<h1>Welcome to Awesome App - Feature B</h1>
>>>>>>> feature-b
Decide how you want to merge the changes. You could choose one version, keep both, or create a new line. Let’s say you want to keep both versions:
<h1>Welcome to Awesome App - Feature A</h1>
<h1>Welcome to Awesome App - Feature B</h1>
After saving your changes, stage the resolved file:
git add index.html
Finally, commit the merge:
git commit -m 'Resolved merge conflict between feature-a and feature-b'
Congratulations! You’ve successfully resolved a Git conflict. Remember, conflicts are a normal part of collaborative work. The more you practice, the more comfortable you’ll become. Keep pushing forward with your coding journey!