Reset other branch to current without a checkout

Viewed 25381

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?

5 Answers

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)

git branch -f destroys the upstream branch info etc. Typing a git update-ref command, which principally operates cleanly, is tedious and error-prone. It could create any kind of nonsense file under .git.

As this operation is needed frequently, do it via a rather safe alias or script:

git reset-other OTHERBRANCHNAME TARGETREF

After adding e.g. this alias to your config:

[alias]
    reset-other = "!f() { git show -s refs/heads/$1 -- && git update-ref refs/heads/$1 $2 && git show -s $1; }; f"

Add from command-line:

git config --global alias.reset-other "!f() { git show -s refs/heads/$1 -- && git update-ref refs/heads/$1 $2 && git show -s $1; }; f"

When the move succeeded to a wrong target by a slip you already have the SHA printed on the screen to move back ...

Related