How do I push a new local branch to a remote Git repository and track it too?
Asked Answered
D

19

5636

How do I:

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

  2. Push the local branch to the remote repository (i.e. publish), but make it trackable so that git pull and git push will work.

Doc answered 4/5, 2010 at 12:58 Comment(3)
just to point out --set-upstream is -uEgesta
lots of answers containing unrelated information (like how to create a branch) and if the answer applies, then information is missing regarding the magic parameters used.Hoashis
my workflow is: git checkout -b branch, git push => it prints an error message containing the command you need to run. then copy/paste that command. :)Photolithography
E
8375

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.

Eccentric answered 3/6, 2011 at 20:50 Comment(11)
It's also worth noting that if you have an existing tracking branch already set on the branch you're pushing, and push.default is set to upstream, this will not do what you think it will do. It will try to push over the existing tracking branch. Use: git push -u origin mynewfeature:mynewfeature or do git branch --unset-upstream first.Wondawonder
I still needed to 'git branch --set-upstream-to origin/remote' in order for 'git status' to correctly report my branch status with respect to the remote branch.Sandblind
For people using Git from Visual Studio: Actually this is that "Publish Branch" in Visual Studio does. After executing git push with -u parameter i can finally see my branch as published in VS UI.Supinate
For those still confused about the concept I like to "THINK" of it that git push -u origin myepicbranchname is equal to git checkout -b myepicbranchname in terms of what it does. Git push does do more but in terms of simplicity this is most likely what you want to know about the two ;)Trafficator
Somewhat annoyingly, I found that git push -u origin branchname wasn't working, but that git push -u --set-upstream origin branchname did. This is with the PoshGit scripts provided with Github for Windows.Farrison
Please bear in mind that if you want your remote branch to have a different name, you should change the name locally first. For example, let's say I have a branch locally named a-named-branch and I want to push it to remote. If I run git push origin new-named-branch I'll get an error that says error: src refspec new-named-branch does not match any. The fix is to run git branch -m new-named-branch and then running git push origin new-named-branch.Mm
You can also use git push -u origin HEADAndra
@Stephane You only need the -u once to initiate tracking. Afterward just use git pushBalcom
@JonathanMoralesVélez changing the local branch is not necessary. You can push your local branch to any remote branch name like so: git push origin local-branch-name:remote-branch-name. Where origin is the name of the remote (often times actually "origin", local-branch-name is the actual name of your local branch name, and remote-branch-name is your desired branch name you want to push to.Kistner
As of git 2.37.0 the remote tracking can by set by default with git config --global --add --bool push.autoSetupRemote true. See the docs.Julian
Is there any particular reason why HEAD isn't the default? git push -u origin sounds perfectly unambiguous in practice.Jourdan
S
577

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.

Smarm answered 20/1, 2014 at 11:36 Comment(5)
and git pull --all pulls it all back elsewhere ? kewlDorinda
Git allows to commit a branch and not push it for very good reasons. Only using git push --all is like dropping a piece of git architecture. If it works for you, it is perfectly ok, great, do it forever. But PLEASE don't recommend others to avoid learning git just because it is a quick way to do things.Behre
This really isn't the right answer and isn't a good tool to be recommending without a real explanation of what it does and what the implications are. Please consider taking this answer down.Spiritual
@Federico @Spiritual Where can one find the dangers of doing git push --all -u?Dannadannel
@Spiritual @ Federico - I've edited it to spell out what I see the dangers are - is that better?Smarm
B
264

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
Buddleia answered 4/5, 2010 at 13:3 Comment(2)
sometimes your need this git push origin -u local_branch:remote_branchCantilena
why does "git push origin -u remote_branch_name " work sometimes and sometimes not?Gaberlunzie
M
187

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>
Mollee answered 24/4, 2015 at 12:9 Comment(2)
git branch <branch-name> and git checkout -b <branch-name> both create a branch but checkout switch to the new branchHomochromous
dude bracket is just to mention you have to replace with whatever branch name you want to create and push.Mollee
A
149

A slight variation of the solutions already given here:

  1. Create a local branch based on some other (remote or local) branch:

    git checkout -b branchname
    
  2. Push the local branch to the remote repository (publish), but make it trackable so git pull and git push will work immediately

    git 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:

    Enter image description here

Aquiculture answered 5/7, 2016 at 8:13 Comment(1)
Thank you :) git push -u origin <branch-name> wasn't working for me but using HEAD instead of <branch-name> worked perfectly :)Kellene
S
126

I simply do

git push -u origin localBranch:remoteBranchToBeCreated

over an already cloned project.

Git creates a new branch named remoteBranchToBeCreated under my commits I did in localBranch.

Edit: this changes your current local branch's (possibly named localBranch) upstream to origin/remoteBranchToBeCreated. To fix that, simply type:

git branch --set-upstream-to=origin/localBranch

or

git branch -u origin/localBranch

So your current local branch now tracks origin/localBranch back.

Skipper answered 20/3, 2017 at 11:13 Comment(4)
git throws error: src refspec <new branch> does not match any. when I try this.Leede
@Leede exactly the same error I'm facing now, I don't understand how to connect the local_branch to remote_branch in github, can someone help on thisMorganne
Thanks for explaining. Was able to under it and it workedFluke
The top one here is the only one that will work if the remote new branch doesn't exist. All other things in here fails for me. New remote branch definition must connect local:remote.Aurify
I
66

git push --set-upstream origin <your branch name>

OR

git push -u origin <your branch name>

Illbehaved answered 28/4, 2022 at 15:15 Comment(1)
It's worth noting that you can save a bit of typing by using -u as an alternative to --set-upstream. referenceFrontage
T
46

edit Outdated, just use git push -u origin $BRANCHNAME


Use git publish-branch from William's miscellaneous Git tools.

OK, no Ruby, so - ignoring the safeguards! - take the last three lines of the script and create a bash script, git-publish-branch:

#!/bin/bash
REMOTE=$1 # Rewrite this to make it optional...
BRANCH=$2
# Uncomment the following line to create BRANCH locally first
#git checkout -b ${BRANCH}
git push ${ORIGIN} ${BRANCH}:refs/heads/${BRANCH} &&
git config branch.${BRANCH}.remote ${REMOTE} &&
git config branch.${BRANCH}.merge refs/heads/${BRANCH}

Then run git-publish-branch REMOTENAME BRANCHNAME, where REMOTENAME is usually origin (you may modify the script to take origin as default, etc...)

Thun answered 4/5, 2010 at 13:3 Comment(5)
this assumes I have ruby installed. no such luck. any other ideas?Doc
the ruby script calls git push and git config command. I used the code of the script to edit my answer. You might used this information to create a small shell script that does the puslishing for you.Buddleia
William's miscellaneous git tools appears to have moved (that link is now dead). A working link is: gitorious.org/willgitPolygenesis
"William's" link broken again; new link seems to be git-wt-commit.rubyforge.orgPinkster
Edited answer to just have the one working link (github.com/DanielVartanov/willgit)Flexor
L
36

Complete Git work flow for pushing local changes to anew feature branch looks like this

Pull all remote branches

git pull --all

List all branches now

git branch -a  

Checkout or create branch(replace <feature branch> with your branch name):

git checkout -b <feature branch>

shows current branch. Must show with * In front of it

git branch      

Add your local changes (. is on purpose here)

git add .

Now commit your changes:

git commit -m "Refactored/ Added Feature XYZ"

Important: Take update from master:

git pull origin feature-branch

Now push your local changes:

git push origin feature-branch
Liv answered 6/9, 2021 at 10:58 Comment(1)
Don't forget the pull request: git-scm.com/docs/git-request-pullHooves
W
35

I suppose that you have already cloned a project like:

git clone http://github.com/myproject.git
  1. Then in your local copy, create a new branch and check it out:

    git checkout -b <newbranch>
    
  2. Supposing that you made a "git bare --init" on your server and created the myapp.git, you should:

    git remote add origin ssh://example.com/var/git/myapp.git
    git push origin master
    
  3. After that, users should be able to

    git clone http://example.com/var/git/myapp.git
    

NOTE: I'm assuming that you have your server up and running. If it isn't, it won't work. A good how-to is here.

ADDED

Add a remote branch:

git push origin master:new_feature_name

Check if everything is good (fetch origin and list remote branches):

git fetch origin
git branch -r

Create a local branch and track the remote branch:

git checkout -tb new_feature_name origin/new_feature_name

Update everything:

git pull
Wheatley answered 4/5, 2010 at 13:4 Comment(7)
William's script I linked to does about the same with the additional option to delete remote branches and some safeguards, tooThun
>to push the local branch to remote repo (publish), but make it >trackable so git pull and git push will work immediately. its what github does automatically when you push your code to their repository :-)Wheatley
This does not respond to the question, the <newbranch> of the original repo is not trackable (and is renamed as <master> is the new repo you clone in step 3).Buddleia
seems kind of overkill. does the git remote add origin make the local branch trackable? is that the key command here?Doc
@Roni Yaniv: no git remote add origin only register a new remote repository. It is just a step needed before pushing your branch to that remote repository (if you don't want to type the whole address each time)Buddleia
well - we already have a remote repo (origin). i need a way to add a new local branch to that repo while making it trackable+pushable+pullable in the process.Doc
In git push origin master:new_feature_name command, master is the branch that you're working on. If you're on a different branch (let's call it oldbranch, and want to push to a newbranch, the command will be like git push origin oldbranch:newbranch .Skipper
W
32

To create a new branch by branching off from an existing branch

git checkout -b <new_branch>

and then push this new branch to repository using

git push -u origin <new_branch>

This creates and pushes all local commits to a newly created remote branch origin/<new_branch>

Widener answered 3/6, 2015 at 20:36 Comment(0)
C
15

For GitLab version prior to 1.7, use:

git checkout -b name_branch

(name_branch, ex: master)

To push it to the remote repository, do:

git push -u origin name_new_branch

(name_new_branch, example: feature)

Clerissa answered 6/12, 2016 at 18:42 Comment(0)
A
12

I made an alias so that whenever I create a new branch, it will push and track the remote branch accordingly. I put following chunk into the .bash_profile file:

# Create a new branch, push to origin and track that remote branch
publishBranch() {
  git checkout -b $1
  git push -u origin $1
}
alias gcb=publishBranch

Usage: just type gcb thuy/do-sth-kool with thuy/do-sth-kool is my new branch name.

Apprehend answered 5/1, 2016 at 10:11 Comment(0)
O
11

You can do it in 2 steeps:

1. Use the checkout for create the local branch:

git checkout -b yourBranchName

Work with your Branch as you want.

2. Use the push command to autocreate the branch and send the code to the remote repository:

git push -u origin yourBanchName

There are mutiple ways to do this but I think that this way is really simple.

Oshiro answered 2/10, 2019 at 10:11 Comment(0)
S
7

Building slightly upon the answers here, I've wrapped this process up as a simple Bash script, which could of course be used as a Git alias as well.

The important addition to me is that this prompts me to run unit tests before committing and passes in the current branch name by default.

$ git_push_new_branch.sh

  Have you run your unit tests yet? If so, pass OK or a branch name, and try again

  usage: git_push_new_branch {OK|BRANCH_NAME}

  e.g.

  git_push_new_branch           -> Displays prompt reminding you to run unit tests
  git_push_new_branch OK        -> Pushes the current branch as a new branch to the origin
  git_push_new_branch MYBRANCH  -> Pushes branch MYBRANCH as a new branch to the origin

git_push_new_branch.sh

function show_help()
{
  IT=$(cat <<EOF

  Have you run your unit tests yet? If so, pass OK or a branch name, and try again

  usage: git_push_new_branch {OK|BRANCH_NAME}

  e.g.

  git_push_new_branch.sh           -> Displays prompt reminding you to run unit tests
  git_push_new_branch.sh OK        -> Pushes the current branch as a new branch to the origin
  git_push_new_branch.sh MYBRANCH  -> Pushes branch MYBRANCH as a new branch to the origin

  )
  echo "$IT"
  exit
}

if [ -z "$1" ]
then
  show_help
fi

CURR_BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$1" == "OK" ]
then
  BRANCH=$CURR_BRANCH
else
  BRANCH=${1:-$CURR_BRANCH}
fi

git push -u origin $BRANCH
Sherbet answered 21/4, 2017 at 13:30 Comment(0)
F
7

I think this is the simplest alias, add to your ~/.gitconfig

[alias]
  publish-branch = !git push -u origin $(git rev-parse --abbrev-ref HEAD)

You just run

git publish-branch

and... it publishes the branch

Flexor answered 16/1, 2021 at 2:54 Comment(0)
C
4

For greatest flexibility, you could use a custom Git command. For example, create the following Python script somewhere in your $PATH under the name git-publish and make it executable:

#!/usr/bin/env python3

import argparse
import subprocess
import sys


def publish(args):
    return subprocess.run(['git', 'push', '--set-upstream', args.remote, args.branch]).returncode


def parse_args():
    parser = argparse.ArgumentParser(description='Push and set upstream for a branch')
    parser.add_argument('-r', '--remote', default='origin',
                        help="The remote name (default is 'origin')")
    parser.add_argument('-b', '--branch', help='The branch name (default is whatever HEAD is pointing to)',
                        default='HEAD')
    return parser.parse_args()


def main():
    args = parse_args()
    return publish(args)


if __name__ == '__main__':
    sys.exit(main())

Then git publish -h will show you usage information:

usage: git-publish [-h] [-r REMOTE] [-b BRANCH]

Push and set upstream for a branch

optional arguments:
  -h, --help            show this help message and exit
  -r REMOTE, --remote REMOTE
                        The remote name (default is 'origin')
  -b BRANCH, --branch BRANCH
                        The branch name (default is whatever HEAD is pointing to)
Cottingham answered 31/12, 2019 at 13:47 Comment(0)
I
4

It is now possible (git version 2.37.0) to set git config --global push.autoSetupRemote true. Also see: Automatically track remote branch with git

Inspiration answered 8/12, 2022 at 14:49 Comment(1)
Thanks, this is exactly what i've been looking for!Pelham
T
2

git push -u origin HEAD

In case you want the remote and local branch to have the same name and don't want to enter the branch name manually

Twodimensional answered 28/12, 2023 at 15:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.