Skip to content
Jabran Rafique

Secret sauces of Git

2 minutes read

I use Git all day. Every so often I get into an awkward spot that needs a command I don't use in my normal workflow.

At Rated People our agile workflow runs on Atlassian JIRA, wired into a lot of other tools for TDD, CD and CI. So that tickets are tracked properly, every commit message has to include a JIRA ticket number. If it doesn't, you get an error and can't push to the remote.

Change the last commit message

Say I forgot the ticket number in the commit I just made. I can't push until the message has one. To edit the most recent commit message I run:

$ git commit --amend

That opens the message in Git's default editor. Edit it, save, and the push goes through.

Set the default editor with $ git config --global core.editor {editor_name}, replacing editor_name with vim, pico, nano or whatever you use.

Change several commit messages

With good music in my headphones I sometimes forget the ticket number on several commits. Amending only fixes the last one, so I use an interactive rebase over the last few commits instead:

$ git rebase -i HEAD~{n}

n is the number of commits to list. It works in two steps.

Step 1

Git opens the list of commits in your editor, one per line, like this:

pick commit_hash commit_message

To change a commit's message, replace pick with reword:

reword commit_hash commit_message

If you delete a whole line, you lose that commit.

The available commands are listed at the bottom:

# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell

Save and close to move on to step 2.

Step 2

Each commit marked reword opens in turn so you can edit its message. Save and exit each one.

Push rewritten commits

If, like me, you'd already pushed, a normal push of the rewritten commits will be rejected. Use --force:

$ git push origin HEAD --force

Delete a remote branch

Sometimes a wrong or unwanted branch ends up on the remote and you can't delete it, perhaps because of limited permissions. This deletes it from the remote for good:

$ git push origin --delete {branch_name}

You CANNOT undo this. A branch deleted from the remote is hard to recover, so back it up first.

Add changes to a commit you've already made

Sometimes I commit and then realise a few more changes belonged in it. A soft reset handles that:

$ git reset --soft HEAD~{n}

n is how many commits to undo. Their changes stay staged. When you've made the extra changes, commit again and reuse the old message with:

$ git commit -c ORIG_HEAD

A nicer Git log

My favourite log command combines a few flags to show the history as a graph:

$ git log -{n} --oneline --stat --color --graph --pretty

n is the number of commits to show.