Accidentally committed to the wrong branch? Here is how to fix it.
If you have made a commit to the wrong branch, there is nothing to worry about. You can easily move the commit to the correct branch. Let me show you how with an example:
Let’s say I made a commit to the main
branch that was meant to be in the feature_1
branch (commit 55f0c29
shown
below).
* 55f0c29 (HEAD -> main) Add settings flag for feature_1
* 4015b6f Provide default for product size
* d8dc31c Add db info to settings
We want to undo that last commit and keep the changes. To do that, we use the reset
command with the --soft
flag.
(main)$ git reset --soft HEAD^
HEAD^
means the commit before where HEAD
is now. In our case 4015b6f
. We use --soft
so that Git preserves our
changes. If we look at Git status we will see that our change is still there:
(main)$ git status
On branch main
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: file.txt
Now we can check out the destination branch and make our commit there. In my case feature_1
branch didn’t exist,
so I am creating it here with the -b
flag:
(main)$ git checkout -b feature_1
Switched to a new branch 'feature_1'
(feature_1)$ git status
On branch feature_1
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: file.txt
(feature_1)$ git commit -m "Add settings flag for feature_1"
[feature_1 ef640e4] Add settings flag for feature_1
1 file changed, 1 insertion(+)
If I look at my Git log I see that HEAD
is pointing to the new commit in the new branch:
* ef640e4 (HEAD -> feature_1) Add settings flag for feature_1
* 4015b6f (main) Provide default for product size.
* d8dc31c Add db info to settings.