It's relatively easy to do, but this is usually not the right way to work. Suppose you have done these, while on your own branch master
:
git add -A
git commit -m "message of commit"
This created a new commit and you'd like to send it to the Git server over at origin
without first creating a new local branch name newbranch
; but you'd like that Git not to call this master
, but rather to call this newbranch
. You can just run:
git push origin master:newbranch
or:
git push origin HEAD:newbranch
The variant with HEAD
works regardless of whether the current branch is named master
.
The reason not to do this is simple enough: your branch name master
(or whatever it may be) now corresponds to the server's newbranch
and you will need to remember to use your local name origin/newbranch
to work with your branch named master
. Your branch named master
is no longer a good way to deal with their branch named master
.
In other words, you now need to keep, in your head, the mapping: "my newbranch
is their master
". Git certainly can be used this way, but eventually you are likely to forget that you are doing this.
If you first create your own branch name newbranch
, like this:
git add -A
git status
# oops, I'm on `master`, and I didn't want that, so:
git checkout -b newbranch
git commit -m "message"
you can then:
git push -u origin HEAD
to send newbranch
to origin
using the name newbranch
over there, so that your newbranch
pushes to their newbranch
which is your origin/newbranch
, and now your newbranch
has origin/newbranch
set up as its upstream, and you don't have to remember anything special.
If you accidentally did commit on your master
and wish to undo that, that's easy enough. For instance, suppose you did:
git add -A
git commit -m "message"
and only then realized: oops, I'm on my master
, you can now do:
git branch newbranch
git reset --hard origin/master
git checkout newbranch
or equivalently (but less churn in your work-tree):
git checkout -b newbranch
git branch -f master origin/master
(this is also one command shorter, so it's better in two ways). You're now in a setup where you are on a new branch newbranch
with your new commit on it, and your existing master
matches your origin/master
again. You can now git push -u origin HEAD
to send the commit and create the new branch name newbranch
on the other Git over at origin
, as before.
Note that if you have run git pull
and it has fetched from origin
and run git merge
—that's what git pull
does; it runs git fetch
followed by git merge
—and you are in a conflicted state, you'll have to either finish or abort (terminate without finishing) the merge before you can proceed. The easiest thing is to abort the merge:
git merge --abort
since everything it did was automated and you can easily have Git just do that again later.