Git: Push Local Branch and Track It

Whether you've been programming for decades or just started out, at some point in your career you'll need to share your changes to a codebase. Or maybe if you're like me, you might just be paranoid and want to store everything in a remote repository, like GitHub, for safe-keeping in case you do something stupid on your local machine.

Either way, there are many ways to do so, one of which would be to push a local branch to a remote repo. In this short article that's exactly what I'll go over.

For now let's assume that you've created a new branch in your repository, possibly to implement a new feature or fix a bug:

$ git checkout -b <branch-name>

Now that you have a new branch for your feature, you make some changes and additions to your code, commit it, and are ready to share it with the rest of your team.

Pushing the branch to the remote repository and tracking the upstream branch can be done in one command:

$ git push -u <repo-name> <branch-name>

As you probably guessed, the branch <branch-name> is pushed to <repo-name> in this case.

One important thing to point out is the -u option. This option is an alias for --set-upstream, which will add an upstream tracking reference for the branch you're pushing.

This is useful since adding this tracking reference, among other benefits, makes the specified remote branch become the default for commands like git pull or git rebase when no other arguments are given.