Skip to content

Instantly share code, notes, and snippets.

@mbjones
Last active May 1, 2025 07:04
Show Gist options
  • Save mbjones/c76a47b74ab892d8e4ca9955fb546b9f to your computer and use it in GitHub Desktop.
Save mbjones/c76a47b74ab892d8e4ca9955fb546b9f to your computer and use it in GitHub Desktop.
git reset is my friend

git reset

I often mess up. Sometimes badly 🀯. git reset is my friend.

Here's the current state of the Metacat repo:

image

Imagine I commit a file to develop. When I look at the log, I see its gotten pretty messy, because the merge commit in main wasn't committed into develop. This makes for a messy tree.

image

What if I want to go back and clean it up? First, I can do a soft reset to return to the state before I did my commit. In this case, the develop branch returns to where it was, and my changes are left uncommitted in the README file. I can run the command git reset --soft ad29acc8 to bring the develop branch back to where it was.

image

Note that my changes are now uncommitted in the README.md file:

image

So, now I can do what I shoud have done before, and merge main into develop to create a clean starting point for new changes.

image

πŸŽ‰ πŸŽ‰ πŸŽ‰ Now I have a clean tree. Note that both develop and main point at the same commit hash:

image

And I can redo my commit (git add README.md; git commit), which results in a linear history with my changes to README:

image

Now I have a clean, linear history, but I added some garbage into develop. What if I want to just go back? This is a job for git reset --hard, which moves the branch back to the original commit and discards all of the changes.

Be careful, you can lose stuff here with no way to get it back!

image

Et voila! We're back where we started. 😎 It's like we were never even here. (Not really, though, appearances can be deceiving.)

image

One last warning. git reset rewrites history. So, this is super useful before you push. Once you've pushed, your history is shared for everyone to see, you can't really use reset like this, and you'll need to be more strategic to cover your tracks. Don't rewrite history in shared repositories, it messes with everyone's day.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment