SoFunction
Updated on 2025-03-02

How to resolve Git commit to the error branch

If you accidentally commit the code to the wrong branch, don't worry, you can follow the steps below to transfer the commit to the correct branch.

Here are the detailed steps:

1. Confirm the current status

First, confirm your current branch and commit record.

git status
git log

2. Switch to the correct branch

Suppose you already know the correct branch name iscorrect-branch

git checkout correct-branch

ifcorrect-branchIt does not exist, you can create it:

git checkout -b correct-branch

3. Apply the commit from the wrong branch to the correct branch

Method 1: cherry-pick (recommended)

This approach works when you have committed multiple commits and just want to apply a specific commit to the correct branch.

First, switch back to the wrong branch and find the hash value of the commit you need.

git checkout wrong-branch
git log

Copy the hash value of the required commit, then switch back to the correct branch and do itcherry-pick

git checkout correct-branch
git cherry-pick <commit-hash>

You can execute it multiple timescherry-pickto select multiple submissions.

Method 2: rebase

This approach works when you want to transfer all commits on the wrong branch to the correct branch.

First, confirm that you are on the wrong branch.

git checkout wrong-branch

Then, perform interactiverebaseoperate:

git rebase -i HEAD~n

innis the number of submissions you want to transfer.

In an interactive editor, transfer all relevant commits frompickChange toedit

Save and exit, then switch everything to the correct branch and apply these commits:

git checkout correct-branch
git cherry-pick <commit-hash>

4. Clean up the wrong branch

Method 1: Reset the wrong branch

If you want to keep the history of the wrong branch, but reset it to a specific state:

git checkout wrong-branch
git reset --hard origin/wrong-branch

Method 2: Delete the wrong submission

If you want to delete the commit on the wrong branch, you can execute the following command:

git checkout wrong-branch
git reset --hard HEAD~n

innIt is the number of commits you want to delete.

5. Force push to remote repository

If these commits have been pushed to the remote repository, you need to force push to overwrite the remote branch:

git push origin correct-branch
git push origin wrong-branch --force

Please note that forced pushes will cover the remote repository's history and should be used with caution and ensure that your team is notified.

With these steps, you can effectively transfer the commits on the wrong branch to the correct branch and clean up the wrong commits.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.