137

I want to push a branch (not the current) without having to check it out first, how can I achieve that ?

this is how I'd do:

#currently in master
git checkout feature
git push origin feature
git checkout master

but checking out feature can cause conflicts, can't I just push another branch than the current one ?

BiAiB
  • 12,932
  • 10
  • 43
  • 63
  • Possibly related with a different solution: https://stackoverflow.com/questions/51342767/push-a-git-branch-to-remote-without-checking-the-branch-out – Xun Yang Dec 10 '18 at 09:56
  • 9
    Note there is a risk associated with this practice: If you have [push hooks](https://githooks.com/), they will run on your current branch instead of the branch you want to push. – Xun Yang Dec 10 '18 at 09:59

1 Answers1

211

Simply:

git push origin feature:feature

Or shorter:

git push origin feature
Lorenz Meyer
  • 19,166
  • 22
  • 75
  • 121
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • 5
    Is it necessary to write `feature:feature` or could you just write `git push origin feature` ? – Glemi Nov 13 '19 at 16:29
  • 6
    @Glemi No it's optional; checkout the refspec bit in [the manual](https://git-scm.com/docs/git-push). – trojanfoe Dec 24 '19 at 12:52
  • 3
    It doesnt work for me,, saying error: src refspec dev does not match any // error: failed to push some refs – toioioi Oct 31 '20 at 08:46
  • If you have git hooks (pre-push) setup, which branch runs the git hooks: the branch you're on, or the branch you're pushing? I believe its the former. Example: if I'm on feature branch but want to push master to origin without having to checkout master first. I believe git hooks will run for feature and not for master. – nodebase Dec 07 '22 at 15:20
  • @nodebase It probably depends how you write the hook script; I am no expert on git hooks but I found an [example](https://gist.github.com/pixelhandler/5718585) that stops force pushes to `master`. – trojanfoe Dec 07 '22 at 17:04