我怎么做:

从另一个分支创建一个本地分支(通过 git 分支或 git checkout -b) 将本地分支推到远程存储库(即发布),但使其可追踪,以便 git pull 和 git push 工作。


当前回答

我创建了一个标签,所以每当我创建一个新的分支,它将按下推和跟踪远程分支。

# 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

使用: 只是用 thuy/do-sth-kool 输入 gcb thuy/do-sth-kool 是我的新分支名称。

其他回答

git push --set-upstream 起源 <你的分支名称>

git push -u 起源 <你的分支名>

为了获得最大的灵活性,您可以使用自定义的 Git 命令. 例如,在您的 $PATH 中的某个地方创建下列 Python 脚本,并以 git-publish 名称进行执行:

#!/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())

然后 git publish -h 将向您展示使用信息:

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)

现在可以(Git 版本 2.37.0)设置 git config --global push.autoSetupRemote true。

我创建了一个标签,所以每当我创建一个新的分支,它将按下推和跟踪远程分支。

# 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

使用: 只是用 thuy/do-sth-kool 输入 gcb thuy/do-sth-kool 是我的新分支名称。

在 Git 1.7.0 或更高版本中,您可以查看一个新的分支:

git checkout -b <branch>

编辑文件,添加和承诺. 然后按下 -u (缩写为 --set-upstream) 选项:

git push -u origin <branch>

Git 在推时将设置跟踪信息。