Reset other branch to current without a checkout

Git

Git Problem Overview


I'm writing some scripts for my Git workflow.

I need to reset other (existing) branch to the current one, without checkout.

Before:

 CurrentBranch: commit A
 OtherBranch: commit B

After:

 CurrentBranch: commit A
 OtherBranch: commit A

Equivalent of

 $ git checkout otherbranch 
 $ git reset --soft currentbranch
 $ git checkout currentbranch

(Note --soft: I do not want to affect working tree.)

Is this possible?

Git Solutions


Solution 1 - Git

Set otherbranch to point at the same commit as currentbranch by running

git branch -f otherbranch currentbranch

The -f (force) option tells git branch yes, I really mean to overwrite any existing otherbranch reference with the new one.

From the documentation:

> -f
> --force >
> Reset to if exists already. Without -f git branch refuses to change an existing branch.

Solution 2 - Git

The workflows you describe are not equivalent: when you perform reset --hard you lose all the changes in the working tree (you might want to make it reset --soft).

What you need is

git update-ref refs/heads/OtherBranch refs/heads/CurrentBranch

Solution 3 - Git

You can sync with this command your branches at any time

$ git push . CurrentBranch:OtherBranch -f

Also without -f it replace this set of commands

$ git checkout OtherBranch
$ git merge CurrentBranch
$ git checkout CurrentBranch

It can be useful when you don't need commit all your files in CurrentBranch and so you can't switch to another branches.

Solution 4 - Git

The other answers are good but a little scary. I'm just providing another option to achieve exactly what was asked for somewhat simply with variations on commands I use every day.

In short, None of these options mess with the current branch you're on or current head.

git branch -C other_branch (force-create other_branch from current HEAD)

To reset other_branch to a branch you're not on...

git branch -C old_branch other_branch (force-create other_branch from old_branch)

To reset other_branch to some_branch on the remote, it's a little bit different...

git pull -f origin old_branch:other_branch (force-pull (which ignores the already-up-to-date stuff) origin/old_branch into local's other_branch)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexander GladyshView Question on Stackoverflow
Solution 1 - GitColin D BennettView Answer on Stackoverflow
Solution 2 - GitP ShvedView Answer on Stackoverflow
Solution 3 - GitDenis KuznetsovView Answer on Stackoverflow
Solution 4 - GitRoboticRenaissanceView Answer on Stackoverflow