Git is tricky. It gets especially tricky when you’ve made a mistake and don’t know what to do next. I’ve compiled some common mistakes I make and how I remedy them.
I staged a file that I shouldn't have
1
git reset <filename>
This is probably the easiest because
Git
lists it when you type
git status
, but it's useful to list it down anyway.
I often end up using it when I have files (like blog drafts) that aren't ready to live in Git yet.
What happens when you
git add .
and your
.gitignore
isn't updated?
When I accidentally stage 192384738 files that I shouldn't have, I just remove the filename and type
git reset
.
That unstages all files.
I want to undo my last commit
1
git reset --soft HEAD~1 <filename>
Sometimes, I commit and then realize I'd rather add something really quick before committing it (like fixing a lint error that I forgot about).
This comes in really handy then.
The command removes the commit but leaves the files in your
staging area.
Using --soft
allows you to keep changes,
as opposed to --hard
which completely discards any changes.
If you want to undo more than one commit, just think of HEAD~n as n commits before
HEAD.
So if you want to undo 3 commits, you'd use git reset --soft HEAD~3
My last 3 commits basically do the same thing
Now this is more of a personal preference. But I generally like to keep my git history clean. This is an idea I've taken from Mislav Marohnic (you should check out his blog, it's great!).
Ever had one of these?
1
2
3
4
Fixed bug
Fixed that bug I thought I fixed
Added something
Fixed that same bug again. Finally.
I’d prefer that my git log not be littered with commits like that. It makes it hard to revert or double check on old code. Before pushing, I do this instead:
1
git rebase -i
The command
will take you to a revert page where you can choose to edit commit messages, squash commits, or drop them completely.
I personally end up using squash quite often.
It's best to do this before doing a push so as not to affect other people,
but if you're desperate, adding
HEAD~n
to the end allows you modify previous commits even if they've been pushed, just force push afterwards.
I want to delete my last push
1
2
git reset --hard HEAD~1
git push -f
This is a bit trickier and definitely shouldn't be used if the repo is shared by multiple people.
However, for personal projects where I don't have to worry about merge conflicts and diverting branches, I've used it on occasion.
The -f
stands for force.
It
disable's Git's checks, so use it sparingly.
Sometimes it can take a while Googling to find just the right Git command to use. Maybe next time you're in trouble you could just check on this list.