Skip to content

Instantly share code, notes, and snippets.

@mvduin
Created October 2, 2016 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvduin/f3cd7e5fa738204f2f9bb3c629560f21 to your computer and use it in GitHub Desktop.
Save mvduin/f3cd7e5fa738204f2f9bb3c629560f21 to your computer and use it in GitHub Desktop.
git rebase --interactive
# oh no...
~/some-git-repo$ git log --oneline
d28077cbfb16 (HEAD -> master) even more changes
7911a300794f more changes
7ede0b52d6eb fixed stuff
b554432cd465 this should never have been committed
532e5d734387 Initial commit
# You committed something bad, and it's not your latest commit either!
# The later changes don't depend on it, so you could easily revert it:
~/some-git-repo$ git revert b554432cd465
[master 4a21e5c437ee] Revert "this should never have been committed"
1 file changed, 2 deletions(-)
# But this would leave a permanent record of your mistake:
~/some-git-repo$ git log --oneline
4a21e5c437ee (HEAD -> master) Revert "this should never have been committed"
d28077cbfb16 even more changes
7911a300794f more changes
7ede0b52d6eb fixed stuff
b554432cd465 this should never have been committed
532e5d734387 Initial commit
# You haven't pushed any of this yet (or noone is downstream), so surely
# there must be a way to fix it?
#
# git rebase --interactive (-i for short) to the rescue!
#
# The argument to pass to git rebase -i is the commit *before* the
# commit(s) you want to undo or edit, which can e.g. be described as
# HEAD^^^^ four commits ago (assuming you didn't revert yet)
# HEAD@{4} same thing
# b554432cd465^ commit before the wrong one
# 532e5d734387 last good commit
~/some-git-repo$ git rebase -i b554432cd465^
# ... a text editor opens ...
#
# Change the keyword before the bad commit from "pick" to "drop":
drop b554432cd465 this should never have been committed
pick 7ede0b52d6eb fixed stuff
pick 7911a300794f more changes
pick d28077cbfb16 even more changes
#
# Save and exit.
~/some-git-repo$ git rebase -i b554432cd465^
Successfully rebased and updated refs/heads/master.
# We did it?
~/some-git-repo$ git log --oneline
1e1950143c7c (HEAD -> master) even more changes
bb079301b686 more changes
1546fdf7d427 fixed stuff
532e5d734387 Initial commit
# Yay \o/
# Note that since you're rewritten history, all later commits have
# a different id than before. If you pushed the mistake then you
# will need to use --force to push this rewrite. Don't push history
# rewrites if anyone is downstream (unless you hate them and there
# aren't enough people downstream to form a lynch mob...)
#
# See also http://justinhileman.info/article/git-pretty/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment