40

There is a repo say ABC/A. I had forked this repo to my own github say ME/A. I was asked to create a branch on ME/A say x (originally there were develop and master). I had to write some code, so I cloned ABC/A and worked on its develop branch. But now when I have to push the code, I cannot push it to ABC/A as i dont have rights to do so. I have to push the code to ME/A. The problem is, I worked on develop branch for ABC/A but I have to push the code to ME/A x branch. Is it possible to push code in such a way?

3 Answers 3

52

Yes, you can push any local branch to any remote branch. The syntax is

git push <remote name, e.g. origin> <local branch name>:<remote branch name>

If your current branch (the one you want to push) is called develop, the command would be

git push ME develop:x
1
  • You also can use git push HEAD:master , while the HEAD points at the top of develop branch Jan 27, 2022 at 8:14
46

The answer by Roman is correct. However, there is an additional step that might not be obvious for some. You will need to first add the remote name and URL of the new repo(Repo you are trying to push to), before pushing to a branch in that repo. This can be done like so;

git remote add <remote name> <remote url>
//For example
git remote add origin2 https://user@github.com/example/new_repo.git

Then you can proceed like in Roman's answer, by pushing to that new repo branch like so

git push origin2 local_branch:new_repo_branch
0

Assume that the name of the remote you are using for ME is called me (git remote -v show will list them).

Then with your branch checked out, do

git push -u me A

where A is the name of the branch. The -u will set your local branch to track the upstream branch on me, so git pull will pull from the right place, and future git pushes will work without additional commands.

2
  • I want to push my changes to remote branch x but my changes are in local branch A. What should I do? Mar 11, 2016 at 12:10
  • If remote branch x already exists, check out remote branch x, merge your changes into it, then push it back.
    – abligh
    Mar 11, 2016 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.