How to create a remote Git branch without creating

2019-02-18 15:59发布

问题:

I'd like to create a new remote branch for later use. The most commonly suggested way seems to be:

git checkout -b newbranch origin/startingpoint
git push origin newbranch

But this will also create the branch locally and put me on it. Is there a way of creating a remote branch without creating it locally and moving onto it?

回答1:

push demands a local ref, though it seems to me now that's a bit arbitrary. But it doesn't care what the local ref is called, you can say what remote name you're pushing to directly, so:

git branch junkname origin/startingpoint
git push origin junkname:newbranch
git branch -d junkname


回答2:

I would like to make twalberg's comment an answer. You can create a remote branch by adding refs/head/ to it:

git push origin origin/startingpoint:refs/heads/newbranch

As torek explains, git push adds refs/heads/ automatically if you have a local branch. If you don't have a local branch, it doesn't know if you want to push to refs/heads/ or to refs/tags/. My version of git says: "we are unable to guess a prefix based on the source ref". By adding refs/heads/ you tell git to create a branch on the remote, not a tag.