How to Resolve a Git Merge Conflict from the Command Line

Git provides 3 types of merging, Fast-Forward, Automatic and Manual. A manual merge is required when git is unable to resolve any conflicts , this results in a merge conflict.
Within this example we will generate a merge conflict and then manually resolve from within the command line.

File

First, lets look at the contents of the file will be generate a conflict on.

11:44:38-felix001~/projects/example (master)$ cat README.md xyz

New Branch/Amend File

Next we create a new branch and update the file.

11:44:52-felix001~/projects/example (master)$ git checkout -b create-conflict
Switched to a new branch 'create-conflict'
11:45:24-felix001~/projects/example (create-conflict)$ sed -i 's/xyz/abc/g' README.md
11:45:46-felix001~/projects/example (create-conflict)$ git commit -am "bad update"
[create-conflict f85beb1] bad update
 1 files changed, 1 insertions(+), 1 deletions(-)

Master Branch/Amend File

We then switch back to the master branch. And change the same line within the file.

11:46:15-felix001~/projects/example (create-conflict)$ git checkout master
Switched to branch 'master'
11:46:22-felix001~/projects/example (master)$ cat README.md
xyz
11:46:35-felix001~/projects/example (master)$ sed -i 's/xyz/123/g' README.md
11:46:49-felix001~/projects/example (master)$ cat README.md
123
11:47:03-felix001~/projects/example (master)$ git commit -am "bad update"
[master 231df4e] bad update
 1 files changed, 1 insertions(+), 1 deletions(-)

Merge

Now when we try to merge our new branch with master, we will create a merge conflict. Merge conflicts must be resolved before we can continue.

11:47:43-felix001~/projects/example (master)$ git merge create-conflict
Auto-merging README.md
CONFLICT (content): Merge conflict in README.md
Automatic merge failed; fix conflicts and then commit the result.
11:48:09-felix001~/projects/example (master|MERGING)$ git status
# On branch master
# Unmerged paths:
#   (use "git add/rm ..." as appropriate to mark resolution)
#
#       both modified:      README.md
#
no changes added to commit (use "git add" and/or "git commit -a")

If we now look at the README file you will see the following,

<<<<<<< HEAD
abc
 =======
123
 >>>>>>> create-conflict

Resolve Conflict

Edit the file so only contains a single update, i.e so it just reads abc. We then commit and the merge conflict is successfully resolved.

11:51:30-felix001~/projects/example (master|MERGING)$ git commit -am "resolve"
[master d5d1c9f] resolve
11:51:42-felix001~/projects/example (master)$ git status
# On branch master
nothing to commit (working directory clean)

Note : To rollback the merge you can run the command git merge –abort

Rick Donato

Want to become a Linux expert?

Here is our hand-picked selection of the best courses you can find online:
Linux Mastery course
Linux Administration Bootcamp
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial