How can I push a local branch to a remote Git repository and set it to track the remote branch?

How can I push a local branch to a remote Git repository and set it to track the remote branch?

Here’s what I need to do:

  1. Create a local branch from another branch (using git branch or git checkout -b).

  2. Push the local branch to the remote repository (i.e., publish it), and set it up to track the remote branch so that git pull and git push will work seamlessly.

Hi Naomi,

In Git 1.7.0 and later, you can create and switch to a new branch with:

git checkout -b <branch>

After making your changes, adding, and committing, push the branch with the -u option (short for --set-upstream):

git push -u origin <branch>

This command sets up the tracking information for the branch during the push.

Before the introduction of git push -u, there wasn’t an option to achieve your goal directly with git push. You had to manually add new configuration settings.

To create a new branch and push it:

$ git checkout -b branchB
$ git push origin branchB:branchB

Then, use the git config command to set up tracking:

$ git config branch.branchB.remote origin
$ git config branch.branchB.merge refs/heads/branchB

Alternatively, you can manually edit the .git/config file to add the tracking information:

[branch "branchB"]
    remote = origin
    merge = refs/heads/branchB

In short, to create a new local branch, use:

git branch <branch-name>

To push it to the remote repository and set up tracking, use:

git push -u origin <branch-name>