Git alias trick: one-liner to undo last commit but keep changes

devops-linux

The Problem

You run git commit -m "wip" a bit too fast, then realize you forgot to add a file or the commit message is wrong. Most developers type out git reset HEAD~1 --soft from memory โ€” or worse, Google it every single time.

There is a cleaner way: a permanent Git alias that lives in your global config and works in any repository on any machine.

The Alias

Run this once in your terminal to register the alias globally:

git config --global alias.undo 'reset HEAD~1 --soft'

From now on, whenever you need to undo the last commit and keep all your changes staged and ready, just type:

git undo

That is it. Your files stay exactly as they were โ€” nothing is lost, nothing is discarded. The commit simply disappears from history while the diff remains in the index.

What –soft Actually Does

Git has three reset modes worth knowing:

  • –soft โ€” removes the commit, keeps changes staged
  • –mixed (default) โ€” removes the commit, keeps changes unstaged
  • –hard โ€” removes the commit and deletes the changes entirely

For the “oops, wrong commit” scenario you almost always want --soft. The --hard flag is the dangerous one โ€” it is unrecoverable without git reflog.

Verify the Alias Was Saved

You can confirm the alias exists in your global Git config:

# List all global aliases
git config --global --list | grep alias

# Expected output:
# alias.undo=reset HEAD~1 --soft

Bonus: Where the Alias Lives on Disk

The alias is stored in ~/.gitconfig. You can open that file directly and copy it to any new server or workstation as part of your dotfiles setup:

cat ~/.gitconfig

# You will see a section like this:
# [alias]
#     undo = reset HEAD~1 --soft

If you manage your dotfiles in an S3 bucket or a private Git repo (a common DevOps habit), just include ~/.gitconfig in that sync and the alias follows you everywhere automatically.

The Pitfall to Avoid

Never run git undo (or any reset HEAD~1) on a commit that has already been pushed to a shared remote branch. Rewriting pushed history forces your teammates to do a hard reset or re-clone. Use git revert HEAD instead when the commit is already public โ€” it creates a new “undo” commit rather than erasing history.

Summary

One command, registered once, saves you a small but real amount of friction every single day. Small aliases like this compound over time โ€” your ~/.gitconfig becomes a personal productivity tool that travels with your dotfiles across every environment you work in.

official docs

Leave a Reply

Your email address will not be published. Required fields are marked *

โ˜• Support us ยท ๐Ÿ’ณ Monobank