I ran into a workflow situation with Git and I’m trying to clean things up without losing any work.
Here’s the scenario: I was working on a development branch and made several local changes. Before I could finish the feature, I needed to switch over to master to demo something. When I tried switching branches, my uncommitted changes carried over and ended up affecting master, which I definitely didn’t want.
To avoid that, I quickly created a commit on my development branch with a message like “temporary commit” and then checked out master for the demo.
Now that the demo is done and I’m back on my development branch, I’d like to git undo last commit keep changes meaning I want to remove that temporary commit from history but still keep all the code changes in my working directory so I can continue working on them.
In other words, I want to get rid of the commit itself, but not lose any of the actual modifications I made to the files.
What’s the best and safest way to do this in Git?
Are there any caveats I should be aware of when undoing a commit like this?
Thanks in advance for the help!
Hey! I’ve done this many times when I just want to “undo” a commit but keep all my changes. The trick is to use a soft reset:
git reset --soft HEAD~1
This moves the branch pointer back one commit, essentially removing the commit from history, but leaves all the code changes staged in your working directory. You can then edit, amend, or recommit them however you like. I personally prefer this when I know I only want to remove the commit but don’t want to touch my changes at all.
Another approach I use is a “mixed” reset, which uncommits your changes and also unstages them, giving you a clean slate to work with:
git reset --mixed HEAD~1
After this, your files still contain all the changes, but they’re no longer staged for commit. I find this helpful if I want to reorganize what I’m going to commit next, maybe split it into smaller commits or rearrange the code before committing again. It’s a little more flexible than --soft for tweaking your work.
If you’ve already pushed the temporary commit to a shared branch, I usually recommend git revert instead of a reset, because it doesn’t rewrite history:
git revert HEAD
This creates a new commit that undoes the last commit. The changes will be removed from the branch history but the code itself can be re-applied or modified. I tend to use this when collaborating with others, so I don’t accidentally rewrite history on a branch that others are working on.