If I understand correctly from your example, what you really want to achieve is to create a commit in branch_b
that makes the state of the repository match exactly that of branch_a
.
In that case, git commit-tree
will do the job:
new_commit=$(git commit-tree -p branch_b -m "my message" branch_a^{tree})
git branch --force branch_b $new_commit
In the commands above, we first create a new commit with branch_b
as the parent and with the same state of the repository as that of branch_a
. We then capture the object id of the new commit in the variable new_commit
to finally have branch_b
point to this new commit, effectively obtaining the same outcome as if we had committed the difference between branch_b
and branch_a
to branch_b
.
Note that git branch
will fail if we are already checked out at branch_b
. In that case, we can use git reset
instead:
git reset $new_commit # use --hard to also reset working directory
Another more traditional approach is to leverage git diff
in combination with git apply
:
git checkout branch_b
git diff --binary branch_b branch_a | git apply --index
git commit -m "my message"
This, however, might fail depending on the state of your working tree, as existing untracked or unstaged changes might cause conflicts when applying the patch.