[git] How do I push a new local branch to a remote Git repository and track it too?

I want to be able to do the following:

  1. Create a local branch based on some other (remote or local) branch (via git branch or git checkout -b)

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

How do I do that?

I know about --set-upstream in Git 1.7, but that is a post-creation action. I want to find a way to make a similar change when pushing the branch to the remote repository.

This question is related to git repository git-branch git-push git-remote

The answer is


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.


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

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>


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...)


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)


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.


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


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.


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 had tracking information to this branch.

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

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>

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

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


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.


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)

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.


Examples related to git

Does the target directory for a git clone have to match the repo name? Git fatal: protocol 'https' is not supported Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) git clone: Authentication failed for <URL> destination path already exists and is not an empty directory SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443 GitLab remote: HTTP Basic: Access denied and fatal Authentication How can I switch to another branch in git? VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio?

Examples related to repository

Kubernetes Pod fails with CrashLoopBackOff Project vs Repository in GitHub How to manually deploy artifacts in Nexus Repository Manager OSS 3 How to return a custom object from a Spring Data JPA GROUP BY query How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts? How do I rename both a Git local and remote branch name? Can't Autowire @Repository annotated interface in Spring Boot How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning? git repo says it's up-to-date after pull but files are not updated Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

Examples related to git-branch

How do I rename both a Git local and remote branch name? How do I create a master branch in a bare Git repository? git switch branch without discarding local changes Git: Merge a Remote branch locally Why call git branch --unset-upstream to fixup? Create a remote branch on GitHub How can I display the current branch and folder path in terminal? Git merge master into feature branch Delete branches in Bitbucket Creating a new empty branch for a new project

Examples related to git-push

Fix GitLab error: "you are not allowed to push code to protected branches on this project"? ! [rejected] master -> master (fetch first) Git - What is the difference between push.default "matching" and "simple" error: src refspec master does not match any Issue pushing new code in Github Can't push to GitHub because of large file which I already deleted Changing the Git remote 'push to' default What does '--set-upstream' do? Git push hangs when pushing to Github? fatal: 'origin' does not appear to be a git repository

Examples related to git-remote

Why does Git tell me "No such remote 'origin'" when I try to push to origin? Git - What is the difference between push.default "matching" and "simple" error: src refspec master does not match any How to connect to a remote Git repository? Changing the Git remote 'push to' default What does '--set-upstream' do? Git: How to remove remote origin from Git repo Git push error: "origin does not appear to be a git repository" How to add a local repo and treat it as a remote repo Git branching: master vs. origin/master vs. remotes/origin/master