So I accidentally made 5 commits to branch "A", but I intended to make it to branch "B". I have also pushed all my commits to the remote/origin. I realized that I have made all commits to wrong branch. Is there any way I can transfer all these 5 commits to branch "B" and make my branch "A" as it was 5 commits ago?
Changing the latest Git commit message If the message to be changed is for the latest commit to the repository, then the following commands are to be executed: git commit --amend -m "New message" git push --force repository-name branch-name.
In order to push a Git branch to remote, you need to execute the “git push” command and specify the remote as well as the branch name to be pushed. If you are not already on the branch that you want to push, you can execute the “git checkout” command to switch to your branch.
Push a new Git branch to a remote repo Clone the remote Git repo locally. Create a new branch with the branch, switch or checkout commands. Perform a git push with the –set-upstream option to set the remote repo for the new branch. Continue to perform Git commits locally on the new branch.
Checkout to A
. Copy and paste the 5 commit hashes anywhere sequentially.
e.g. 5 (oldest) -> 4 -> 3 -> 2 -> 1 (newest), assume 1 is your top commit of git log
command.
$ git checkout A
$ git log
# copy the 5 commit hashes
Checkout to B
and take (cherry-pick) 5 commits into B
branch.
$ git checkout B
$ git cherry-pick <commit-hash>
# repeat 5 times with new commit hash each time (old to new)
# Or, you can cherry-pick a range of commits by 'git cherry-pick <from-commit>^..<to-commit>', note '^' sign
$ git cherry-pick <commit-5>^..<commit-1>
Now, Undo (hard reset
) the latest 5 commits from A
. Note, hard reset will change your A's git history (if there is anyone else pulled A branch already locally then you can use revert
instead hard reset
). so, force push is needed to push the branch A
.
$ git checkout A
$ git branch A.bac # backup branch 'A' for safety
$ git reset --hard HEAD~5 # undo last 5 commits from branch A
$ git push -f origin HEAD # need force push since history is changed
Note: The basic form of cherry picking a range of commits is:
$ git cherry-pick abc1234..def5678
abc1234
is the oldest commit and def5678
is the newest commit. abc1234
is not included in the commit but def5678
is included. If you want to include abc1234
then start the range from the previous commit of abc1234
by putting a ^
after abc1234
like:
$ git cherry-pick abc1234^..def5678
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With