Question

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

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?


Submit an answer


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!

Sign In or Sign Up to Answer

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.

Bobby Iliev
Site Moderator
Site Moderator badge
October 18, 2024
Accepted Answer

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

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

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.