0

I needed to move some commits to another, new branch, and I followed the instructions in this answer.
So, as mentioned in the linked question, I went from:

old_branch A - B - C - D - E

to this

new_branch       C - D - E
                /
old_branch A - B 

The problem is that now, if I make changes and try to run "git push" from new_branch, I'm getting the error:

fatal: The upstream branch of your current branch does not match
the name of your current branch.  To push to the upstream branch
on the remote, use

    git push . HEAD:old_branch

To push to the branch of the same name on the remote, use

    git push . HEAD

I tried running:

git remote show origin

and I got

* remote origin
  Fetch URL: xxx.git
  Push  URL: xxx.git
  HEAD branch: master
  Remote branches:
    new_branch                         tracked
    old_branch                         tracked
    master                             tracked
  Local branches configured for 'git pull':
    old_branch                         merges with remote old_branch
    master                             merges with remote master
  Local refs configured for 'git push':
    new_branch                         pushes to new_branch (up to date)
    old_branch                         pushes to old_branch (up to date)
    master                             pushes to master     (up to date)

If I try checking:

git status

I got:

On branch new_branch
Your branch and 'old_branch' have diverged,
and have 6 and 3 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

I can push the code to the new_branch by using git gui, but how can I fix this so that I can git push as well?

Carlo
  • 1,321
  • 12
  • 37
  • Note that you currently have a (local) branch name set as the upstream of some other (local) branch name. This is a valid thing to do in Git! It's just pretty rare for anyone to *want* to do it. As [LeGEC answered](https://stackoverflow.com/a/72939559/1256452), the cure is to tell Git that this is the wrong upstream—that `new_branch` should have a different upstream set. – torek Jul 11 '22 at 23:11

1 Answers1

2

From the information you display : your local new_branch branch is not tracking the branch you expect.

Set the correct remote tracking branch for your local new_branch branch :

git branch -u origin/new_branch new_branch

note that this upstream branch is only used to provide a default value when you run git push with no extra argument.

You can always explicitly name the remote branch you want to push to :

git push origin new_branch:new_branch

# could also be :
git push origin new_branch:any_branch
git push origin new_branch:refs/tags/any_tag

You can also update the tracked branch while running a git push :

git push -u origin new_branch:new_branch
LeGEC
  • 46,477
  • 5
  • 57
  • 104