Git Branch

Creating & Working With Git Branches

In Git, a branch is a new/separate version of the main repository.

When creating a new branch, all Git needs to do is create a new pointer and doesn't change the repository in any other way.

Note: Git only creates a new branch. To start adding commits to it, you need to select it with git checkout, and then use the standard git add and git commit commands.

Now, we create a new branch :

$ git branch hello-world-images

And confirming if we have successfully created a new branch :

$ git branch
 hello-world-images
* master

We can see the new branch with the name "hello-world-images", but the * beside master specifies that we are currently on that branch.

checkout is the command used to check out a branch branch. Moving us from the current branch, to the one specified at the end of the command:

$ git checkout hello-world-images
Switched to branch 'hello-world-images'

Branches allow you to work on different parts of a project without impacting the main branch. When the work is complete, a branch can be merged with the main project. You can even switch between branches and work on different projects without them interfering with each other. Branching in Git is very lightweight and fast!


Creating Remote Branches in Git

So far, we only demonstrated local branch operations. In order to operate on remote branches, a remote repo must first be configured and added to the local repo config. You can push an existing local branch and thereby publish it on a remote repository.

With the correct local branch checkout , you can publish it on a remote repository - thereby "creating" it on that remote:

$ git push -u origin <branch-name>

Please mind the "-u" option: it establishes a "tracking relationship" between the existing local and the new remote branch.