Published on

What to do if you accidentally commit to the master branch

Authors
  • avatar
    Name
    hwahyeon
    Twitter

If you've accidentally committed changes to the master branch, you'll be able to solve with three steps.

Step 1: Create a new branch (git branch new-branch)

First, create a new branch to store the changes you mistakenly committed. Here, new-branch is an arbitrary name you can choose.

git branch new-branch

This creates a new branch based on the current commit in the master branch, so your mistakenly committed changes will now be saved in this new-branch.

Step 2: Switch back to the master branch (git checkout master)

git checkout master

Switch back to the master branch to remove the mistaken commit.

Step 3: Reset the master branch to the previous commit (git reset HEAD~ --hard)

The git reset command changes the state of the branch to a specific commit. HEAD~ refers to the commit immediately before the current one, and the --hard option removes any changes made after that commit.

git reset HEAD~ --hard

This command resets the master branch to its state just before the last commit, effectively removing the mistakenly committed changes from master. However, since the changes are already saved in the new branch, they won’t be lost.

Undoing multiple commits

If you’ve made multiple commits by mistake, you can specify the number of commits you want to undo. For example, to undo the last 3 commits, run:

git reset HEAD~3 --hard

Here, HEAD~3 refers to the last three commits.

Using the hash ID

Alternatively, if you know the hash ID of the specific commit you want to reset to, you can use:

git reset <commit-hash> --hard

After running this command, all of the mistakenly committed changes will remain in the new-branch, and the master branch will be restored to its previous state.

Removing an Unnecessary Commit

If you don't need the contents of your latest commit, you can simply use git reset to remove it without creating another branch.

git checkout master
git reset HEAD~ --hard