This post is based on Dangit, I accidentally committed something to master that should have been on a brand new branch!
Problem
Let’s say you have just set up a new git repository. Initially, you planned to create a new branch named “test” to work on after the first commit, which involved editing the README.md file. However, in practice, you continued to make changes on the main branch instead.
▶ What I originally planned to do
▶ What I’ve actually done…
Solution: using git reset
▶ Steps
- Create a new test branch based on the current HEAD state.
- Reset the main branch to the state immediately after the first commit.
- Switch to the test branch.
▶ Commands
## Step 1
% git branch test
## Step 2
% git reset 813faa2 --hard
## Step 3
% git switch test
▶ Explains
- You can create a new branch based on the current HEAD without switching using
git branch <branch-name>
. - Using
git reset --hard
instead ofgit reset --soft
ensures that by default, changes are not left in the current branch’s index or files. - If changes remain in the current branch, you would need to execute
git stash
orgit clean
.
!!WARNING
If you have already pushed to the remote repository with the wrong commits, it’s better not to execute the above solution because it could inconvenience other developers.