I was looking to learn a bit more about the parts of git I’ve not ventured into yet. What better way that looking the most common ways people screw them up and how to fix the resulting problems! Here’s a short list, compiled from my own experience and issues I’ve come across on the Internet.

I wrote the wrong thing in a commit message

If the commit hasn’t been push you can do the following, which will allow you to edit the message on the most recent commit:

git commit --amend

How can I undo the last commit?

You can use git reset e.g.:

git reset --hard HEAD~1

HEAD~1 means HEAD-1 commit. It should be noted that this is the nuclear option, and any changes you made will be discarded. If you want to keep your changes in the working tree use:

git reset --soft HEAD~1

If you’ve already published your commits, you should use revert. This is create new commits undoing the last change:

git revert HEAD~1..HEAD
git revert commitid

Delete a Git branch remotely

git push origin --delete branchname

What are the differences between ‘git pull’ and ‘git fetch’?

git pull, is git fetch followed by git merge. git fetch gets the remote changes, they get kept under refs/remotes//. However it doesn’t affect your local branches, and won’t change your working copy. git pull then merges these changes with the local copy.

How do I undo a ‘git add’ before committing

You did a “git add filename” accidentally and want to undo it before committing your change. You can simply do:

git reset filename

To unstage your changes to that file.

How do I deal with merge conflicts

Use “git mergetool” which gives a handy interface for solving merge conflicts.

Remove all local untracked files (and directories) from your local clone

Careful! You might want to take a backup before doing this:

git clean -f -d

Clone all remote branches

You probably already have, they’re just hiding! Use the following to see all the branches:

git branch -a

You can then use “git checkout origin/branchname” to take a look at the branch. Or “git checkout -b branchname origin/branchname”. To create a local tracking branch.

Rename local branch?

git branch -m oldname newname

Revert to a previous Git commit

You can use reset as above to revert to a previous commit, this assumes you mean go back to where you were before permanently rather than just take a look (for that you want to checkout an old version). The commit ID, should be as shown in the output of “git log”.

git reset --hard commitid

Again this will discard all changes in your working tree, so make sure this is really what you want to do! Or look at using –soft rather than –hard.

Remove a git submodule

Creating a submodule is pretty straight-forward, but deleting them less so the commands you need are: