How do I push a new local branch to a remote Git repository and track it too?
Solution 1
In Git 1.7.0 and later, you can checkout a new branch:
git checkout -b <branch>
Edit files, add and commit. Then push with the -u
(short for --set-upstream
) option:
git push -u origin <branch>
Git will set up the tracking information during the push.
Solution 2
If you are not sharing your repo with others, this is useful to push all your branches to the remote, and --set-upstream
tracking correctly for you:
git push --all -u
(Not exactly what the OP was asking for, but this one-liner is pretty popular)
If you are sharing your repo with others this isn't really good form as you will clog up the repo with all your dodgy experimental branches.
Solution 3
Prior to the introduction of git push -u
, there was no git push
option to obtain what you desire. You had to add new configuration statements.
If you create a new branch using:
$ git checkout -b branchB
$ git push origin branchB:branchB
You can use the git config
command to avoid editing directly the .git/config
file:
$ git config branch.branchB.remote origin
$ git config branch.branchB.merge refs/heads/branchB
Or you can edit manually the .git/config
file to add tracking information to this branch:
[branch "branchB"]
remote = origin
merge = refs/heads/branchB
Solution 4
Simply put, to create a new local branch, do:
git branch <branch-name>
To push it to the remote repository, do:
git push -u origin <branch-name>
Solution 5
A slight variation of the solutions already given here:
Create a local branch based on some other (remote or local) branch:
git checkout -b branchname
Push the local branch to the remote repository (publish), but make it trackable so
git pull
andgit push
will work immediatelygit push -u origin HEAD
Using
HEAD
is a "handy way to push the current branch to the same name on the remote". Source: https://git-scm.com/docs/git-push In Git terms, HEAD (in uppercase) is a reference to the top of the current branch (tree).The
-u
option is just short for--set-upstream
. This will add an upstream tracking reference for the current branch. you can verify this by looking in your .git/config file: