« back

You Should Really Branch Out a Bit-Part 1

18 Sep 2012

Let's go out on a limb.

Today, let's look at some useful commands when dealing with branches and talk about some ways you can fall out of the tree if you don't know what you are doing. Since using branches can be a powerful tool, here are some reasons you may want to use a new branch...

1. Experimental changes.

2.New features.

3.Bug fixes.

Renaming a branch: (In all examples, this $> will stand for your prompt on the command line.) Let's say you have your master branch called master but you want to rename it to main. You can do that by using the -m command(which stands for move) and passing it two arguments. The first argument will be the name of the branch that you want to change and the second will be the new name that you want to give to that branch.

1     $> git  branch -m master main

To change it back you can simply use the same command and reverse where the names are.

Creating a new branch: Simply use git branch and pass the name of the branch you want to create. Be careful!- Creating a new branch does not mean that you are using it. You need to switch to it.

1     $>git branch the_name_of_the_branch_you_want_to_create

Viewing the names of your existing branches: To view the names of the branches that you have, you can use the git branch command and it will list them all. The one that you are currently using will have an asterisk next to it.

1     $>git branch 
3      branch 1
4     *branch 2
5      branch 3

Switching to a a different branch that you have already created: You use the checkout command and tell it the branch you want to use.

1     $> git branch checkout the_name_of_the_branch_you_want_to_use

To combine creating a new branch and switching to it all at once:

1     $>git checkout -b the_name_of_the_branch_you_want_to_create_and_be_using

There is an optional parameter you can pass. By default the branch will be created from the branch that you are on. If you want to create your branch based off of a different branch, you can pass the branch that you want you new branch to be created from.

1     $>git checkout -b name_of_branch_you_want_to_create_and_be_using name_of_branch_you_want_your_new_branch_to_be_made_from

Before we end part one, there is one last thing I would like to talk about. If you want the security of having your code stored somewhere else besides your computer, then you will probably be tempted to push. This idea can be misleading in git. If you just use the git push command, you will push to master. You need to specify that you want to push to the branch you are working on.

You can do it like this:

1     $> git push origin the_branch_you_want_to_push_to

There you have it. You should be up and running with branches. In part two we will look at how to deal with

comments powered by Disqus