How to set upstream branch to the same name as the branch
Configure git config
$ git config --global push.default current
Now, after checkout to a branch, you should use simply git push
$ git checkout -b new-branch
$ git push # similar to git push -u origin new-branch
If you want to set upstream for the future then use --set-upstream
(-u) flag:
$ git push -u origin HEAD
N.B. HEAD and local current branch normally stay in the same state.
There's some handy git commands that can help out here.
git rev-parse --abbrev-ref HEAD
-> returns the current branch name
git branch -u <remote>/<branch>
-> sets the current branch to track <remote>/<branch>
I do this sort of thing a lot and leverage aliases to help me out.
alias gph='git push origin $(git rev-parse --abbrev-ref HEAD)'
alias gbuh='git branch -u origin/$(git rev-parse --abbrev-ref HEAD)'
Reference:
- OG answers on getting the name of the current branch newer post and OG post
[Edit] sajib khan's first answer, setting push.default
to current
will enable pushing, but does not actually set the upstream. This means that after a future git fetch
, your Git won't report ahead/behind counts, and your Git won't know the upstream to use for git rebase
or git merge
(or git pull
either though I advise avoiding git pull
).
You can use [edit, as in the second part of his answer]:
git push -u origin HEAD
If needed, this creates the branch on the other Git, so that your Git acquires the origin/
variant. Then in any case it sets that (maybe new) remote-tracking branch you have as your branch's upstream. But until origin/feature/long-branch-name-I-dont-want-to-have-to-type-out
actually exists, you can't set it as the upstream.1
1Actually, you can, you just can't use git branch --set-upstream
to do it. And, you don't want to type it in again anyway. To do it "manually" you would need:
git config \
branch.feature/long-branch-name-I-dont-want-to-have-to-type-out.remote origin
git config \
branch.feature/long-branch-name-I-dont-want-to-have-to-type-out.merge \
feature/long-branch-name-I-dont-want-to-have-to-type-out
which means typing it out three times (!), or writing yourself a script.