Sitemap
DEV Amarjit Singh Sodhi

DEV Amarjit Singh Sodhi

Revert commit changes from git

2 min readDec 8, 2023

“If you got here, then I assume you are in trouble…”

Press enter or click to view image in full size

It seems you have mistakenly overwritten the code at the wrong branch by adding one or more commits. And now you want to get back the code that resided in the concerned branch before the recent commits.

To make this easy, let’s create a scenario and at the end of this article try to relate this to your case.

Let’s assume you have two branches named “feature/profile” & “feature/product”.

And you have overwritten the code of the “feature/profile” branch with code that shall belong to the “feature/product” branch.

STEPS TO FOLLOW

Step 1

First thing first, take the local backup of your project.

Step 2

Open the terminal at the root folder of your project and check for untracked changes with the help of “git status” command. If you see uncommitted changes or untracked files then create a local commit.

Step 3

Get DEV Amarjit Singh Sodhi’s stories in your inbox

Join Medium for free to get updates from this writer.

Use “git checkout -b {new_branch_name} {commit_id}”

NOTE: “new_branch_name” is the name of the branch that will act as the backup branch of the desired code. And “commit_id” is commitId of the last commit that was pushed before the unwanted commits.

This command will create a new branch that will create the copy of the code from the mentioned commitId.

Now you have safely extracted the desired code.

Now it’s important to erase those unwanted commits to avoid any confusion and to make your commit history clean.

Step 4

Checkout into the “feature/profile” branch since those commits belong to this branch.

Step 5

Use “git reset –hard {commit_id}” to reset the commits to specific commitId. After this you can notice that the changes from the specific commit have come to your local “feature/profile” branch.

Step 6

Now you completely erase the unwanted commits from the commit history, use git push command.

Press enter or click to view image in full size

Now you can smile because the trouble is long gone!!

--

--