Using Branches in Git

Git allows you to do work in new “branches” separate from your main “master” branch. In effect, “checking out” branches in Git means actually copying and swapping your working directory files, so you can change them as you please, and switch back to another branch later.

This means you can do as much testing and tinkering as you need without affecting your project. Later, you can merge changes from one branch into another. In this article, we’re going to discuss using branches effectively.

Typical Use Cases

We will go through two typical use cases for the branching feature. In both of these cases it will be important to keep our working directly clean and work in a separate branch. When changes are finalized, they can be merged back into a “master” branch and pushed to a production repository.

Testing a New Feature

An example of a typical situation involves a “master” branch, which is pushed to your production repository. Locally, if you want to test a new feature without affecting the master, you can create a new branch called “test”. The files in your working directory are bsically an exact copy of the master files, which you can alter as needed. If you like the changes you’ve made, you can switch back to “master” and merge the “test” changes into “master”.

Applying a Quick Fix

Likewise, imagine you are working on “test” but you receive an urgent request to apply a fix. You can switch back to master and “check out” a new branch called “fix”. Once you have applied the fix, switch back to master, merge “fix” into “master” and push changes to the production repository. Then, you can go back to “test” and keep working.

  1. In your working directory, apply the following command to create and “check out” your files to a new branch:
     git checkout -b fix
  2. Having created a new branch, it is safe to edit the files
  3. Once the fix has been applied, commit the changes:
     git commit -am "fixed that broken thing"
  4. Now that changes have been made and tested, switch back to the master branch:
     git checkout master
  5. Merge the fix branch with master:
     git merge fix

The steps for merging the “fix” and “test” branch will be the same.

Christopher Maiorana Content Writer II

Christopher Maiorana joined the InMotion community team in 2015 and regularly dispenses tips and tricks in the Support Center, Community Q&A, and the InMotion Hosting Blog.

More Articles by Christopher

Was this article helpful? Join the conversation!