Git Branching and Merging

Posted on August 02, 2018


When you commit your staging into Git, you are essentially saving your changes into the current branch. Git allows developers to create multiple copies of a repo that represents different lines of development from the same source code. When a repo is initialized, a default branch named master is automatically created and used as the active branch. We can see the current active branch in the Git Bash interface, or by running git status

Current Git branch
Current Git branch

To create a new branch, we can use the branch command

$ git branch develop

Then we can switch the current active branch with checkout command

$ git checkout develop

Create new git branch and switch to it
Create new git branch and switch to it

The new branch will be created using the latest commit made from the previous branch. In this case, master will be a copy of develop. Let's make some changes in develop branch

$ echo "A test file" > DEVELOPFILE.txt

Now add it to staging and commit it. To add all files without typing the name, you can use git add .

$ git add .
$ git commit -m 'commit develop'

Create another branch named feature and checkout into it. Alternatively, we can use the checkout command to create a new branch and checkout at the same time.

$ git checkout -b feature

Now if you run git log, it will show the commit from develop repo. But if you checkout into master and run git log, the same commit will not appear.

Git log differences
Git log differences

Just remember that a new branch will always take the commit history of the previously active branch, so if you want to create branches from master and not develop you need to first make sure the active branch is master before checking out.

Merging branches

Now that develop branch has committed its changes, we can update master branch so that it receives update from develop branch. A merge is the process of updating the currently active branch with changes from the target branch. For example, let's merge develop into master branch.

$ git merge develop

This will update our master branch to be even with develop branch.

Share this:
LinkedIn
Reddit
WhatsApp

Get Free Guides