Report this

What is the reason for this report?

I accidentally pushed code to the main git branch. How can I recover or undo the changes?

Posted on October 18, 2024

I accidentally pushed some code changes directly to the main branch without creating a separate feature branch. Is there a way to undo this and recover the previous state of the branch? What can I do to revert or reset the commit without causing any issues for other collaborators?



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hey there! 👋

No worries, you can definitely recover from this! Here’s what you can do depending on the situation:

If you just need to undo your last commit and don’t mind losing the changes, you can reset the branch to the previous state before the push:

git reset --hard HEAD^

This will remove the last commit locally. After that, force-push the branch to update it on the remote:

git push origin main --force

If the commit was already pushed and you don’t want to rewrite history (especially if others are working on the same branch), it’s better to use git revert to create a new commit that undoes the changes:

git revert HEAD

Then, push the new commit:

git push origin main

This way, you don’t mess with the history and keep everything safe for your team!

Going forward, I recommend setting up branch protections for your main branch to avoid direct pushes. You can configure it to require pull requests for merging into main, which helps prevent accidental pushes in the future!

Here’s a quick link on how to set branch protections: Branch protection rules on GitHub

Let me know how it goes!

- Bobby

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.