Sharing git branches

I’ve been learning git lately. Here are a few tips for sharing branches I’ve collected during the past few weeks.

Create a branch

In git, branches are stored on your local machine. Even the commonly named “master”, is just a branch on your local machine. Master is simply set up to track a branch on a remote machine by default. To create a new local branch, you can do one of two things. Create the branch and then check it out, or do a checkout with a branch switch.

# using the branch tag
$ git branch newbranch
$ git checkout newbranch
# or just do it with checkout first
$ git checkout -b newbranch
# you can look at your local branches
$ git branch

Pushing a branch to the server

This is only applicable for using git with a central server to track changes. You can of course, use the same method to push a branch to another machine that isn’t being used as a central server (like another development machine) but I haven’t done that as much.

$ git push origin newbranch
# You can look at the new branch on the server
$ git branch -r

Checkout a remote branch

If someone else has pushed a branch to the server, you can check it out on your machine.

$ git checkout -b newbranch origin/newbranch

NOTE There is a –track switch on the checkout command you might need to add. For me, it has been doing that by default though.

NOTE After you push a branch to a server, your local branch isn’t set up to track changes on that branch. There may be another way to accomplish getting that set up, but I just check out the branch again.

$ git push origin newbranch
$ git checkout -b newbranch_renamed origin/newbranch

You could of course, delete “newbranch” and then re-checkout the branch to the same name. It’s important to realize that the names don’t matter really. Newbranch can be named differently on the local and remote machine.

Deleting branches

To delete a branch, just use the -d switch on branch.

$ git checkout master # or another branch
# do your merging before you do the delete 
$ git branch -d newbranch
# you can delete the remote branch after you have deleted the local one like this:
# the syntax is slightly confusing, but it works
$ git push origin :newbranch 
This entry was posted in Programming and tagged , , , . Bookmark the permalink.

4 Responses to Sharing git branches

  1. Daniel says:


    I couldn’t find this information any were else on the net! Thanks very much.

  2. Pingback: Kai’s daily tech #43 … | Kai Richard König

  3. Pingback: 很有用总是忘的Git命令 | To the Great National Parks!

  4. jesselee34 says:

    Thanks!!!! You are awesome!

Leave a Reply

Your email address will not be published. Required fields are marked *