DEV Community

Cover image for Oops, I Committed to the Wrong Branch (And How to Fix It Fast)
Md. Abdur rahman
Md. Abdur rahman

Posted on

Oops, I Committed to the Wrong Branch (And How to Fix It Fast)

So, you just spent hours knocking out a fix. You committed the code, felt like a genius, and then realized your mistake: you did all that work directly on the dev branch instead of creating a feature branch first.

Don't panic. You don't need to manually copy-paste your changed files into a folder on your desktop. Git can fix this in seconds.

Here is exactly how to move your work over to a new branch (let's call it bugfix_order_module), whether you've kept those commits local or accidentally pushed them to the remote server.

Scenario A: You haven't pushed to remote yet
This is the easiest fix. Your commits are sitting on your local machine, and the remote dev branch is completely untouched.

Open your terminal (make sure you are on dev and have no uncommitted changes) and run this:

# 1. Create a new branch that copies your current state
git branch bugfix_order_module

# 2. Rewind your local dev branch back to match the remote server
git reset --hard origin/dev

# 3. Switch over to your new, safe branch
git switch bugfix_order_module
Enter fullscreen mode Exit fullscreen mode

Why it works: You basically stamped a bookmark (bugfix_order_module) on your newest code, then forced your dev branch to rewind back to the state of the server. Your code is safe, and dev is clean.

**Scenario B: You already pushed to the remote server
**Okay, so you ran git push, and now those commits are officially on the remote dev branch.

Disclaimer: If you work on a team and other people are actively pulling from dev, ask your lead before doing this! Force-pushing can mess up your coworkers' local branches. If you are clear to proceed, here is how you rewrite history:

# 1. Save your work by creating the new branch
git branch bugfix_order_module

# 2. Rewind local dev branch by exactly 4 commits (change the 4 to however many you made)
git reset --hard HEAD~4

# 3. Force push this clean state to the remote server 
git push --force origin dev

# 4. Switch to your new branch
git switch bugfix_order_module

# 5. Push your new branch to the server normally
git push -u origin bugfix_order_module
Enter fullscreen mode Exit fullscreen mode

Why it works: You saved your work locally just like before. But instead of matching a clean remote, you manually wound your local dev branch back by 4 commits (HEAD~4). Then, the --force flag told the remote server, "Hey, overwrite your history with my new, clean history." Run a quick git log and you'll see your code exactly where it belongs. Back to work!

Top comments (0)