Close

Git - Merging Branches

[Updated: Apr 27, 2020, Created: Apr 27, 2020]

The following command allow us to merge a target branch into the current branch

git merge <target-branch>

Example

Let's start Git Bash for windows and add a project to Git:

Joe@jpc MINGW64 ~
$ mkdir example-project

Joe@jpc MINGW64 ~
$ cd example-project/

Joe@jpc MINGW64 ~/example-project
$ git init
Initialized empty Git repository in C:/Users/Joe/example-project/.git/

Joe@jpc MINGW64 ~/example-project (master)
$ echo a > test.txt

Joe@jpc MINGW64 ~/example-project (master)
$ git add -A && git commit -m "adding test.txt"
[master (root-commit) 384becb] adding test.txt
 1 file changed, 1 insertion(+)
 create mode 100644 test.txt

Let's create a new branch (XYZ), switch to it and make changes to our file 'test.txt'

Joe@jpc MINGW64 ~/example-project (master)
$ git checkout -b XYZ
Switched to a new branch 'XYZ'

Joe@jpc MINGW64 ~/example-project (XYZ)
$ echo b >> test.txt

Joe@jpc MINGW64 ~/example-project (XYZ)
$ git add -A && git commit -m "new changes"
[XYZ eed6ad3] new changes
 1 file changed, 1 insertion(+)

Joe@jpc MINGW64 ~/example-project (XYZ)
$ git status
On branch XYZ
nothing to commit, working tree clean

Joe@jpc MINGW64 ~/example-project (XYZ)
$ cat test.txt
a
b

Let's switch back to 'master':

Joe@jpc MINGW64 ~/example-project (XYZ)
$ git checkout master
Switched to branch 'master'

Joe@jpc MINGW64 ~/example-project (master)
$ cat test.txt
a

Create another branch (ABC)

Joe@jpc MINGW64 ~/example-project (master)
$ git checkout -b ABC
Switched to a new branch 'ABC'

Switch to master and merge XYZ

Joe@jpc MINGW64 ~/example-project (ABC)
$ git checkout master
Switched to branch 'master'

Joe@jpc MINGW64 ~/example-project (master)
$ git merge XYZ
Updating 384becb..eed6ad3
Fast-forward
 test.txt | 1 +
 1 file changed, 1 insertion(+)

Joe@jpc MINGW64 ~/example-project (master)
$ git status
On branch master
nothing to commit, working tree clean

Joe@jpc MINGW64 ~/example-project (master)
$ cat test.txt
a
b

Switch back to branch ABC

Joe@jpc MINGW64 ~/example-project (master)
$ git checkout ABC
Switched to branch 'ABC'

Joe@jpc MINGW64 ~/example-project (ABC)
$ cat test.txt
a

See Also