Alex headshot

AlBlue’s Blog

Macs, Modularity and More

Git Tip of the Week: Aliases

2011, git, gtotw, tip

This week's Git Tip of the Week is about creating shorthands for commonly used commands. You can subscribe to the feed if you want to receive new instalments automatically.

Aliases

There are frequently times when you want to be able to perform the same git command repeatedly, often with the same arguments. Whilst it's possible to write shell scripts or use shell aliases in order to be able to remember these, these may sometimes not be sufficient.

The git command line can be configured to use its own aliases for commonly used tasks. Aliases are stored in git config files, which include ~/.gitconfig and path/to/project/.git/config. As a result, it's possible to store aliases in a per-project as well as a global state.

To set up an alias, you can either edit the git config file directly, or run git config --global or git config for the global or per-project settings respectively. An alias is configured as follows:

git config --global alias.ci commit
git conifg --global alias.cia commit -a
git config alias.hub push github

In the example above, running git ci has the same effect as git commit, and git cia has the same effect as git commit -a. Since these are --global properties, these commands will work on any repositories on the same machine.

The git hub command then becomes a push to github, but because of the lack of the --global flag, it only affects the repository that you're working in.

Alias expansion

Sometimes it's desirable to execute multiple git commands, which the short alias form doesn't allow. Or you might want to do something with the result, like pipe it through an alternative utility. That's where the shell aliases can help.

If a git alias is prefixed with an exclamation point, then the alias is expanded as if the entire command had been given on the command line. This allows you to do pipe or sequence operations which can be quite handy:

# Define 'git last' to show last commit message
git config alias.last show -s HEAD^{commit}

# Now lastwc is the word count of that message
git config alias.lastwc '!git last | wc'

# We can also prune off headers and pipe to 'pbcopy'
# which puts it in the clipboard on OSX
git config alias.lastcopy '!git last | tail -n+5 | pbcopy'

These expansions also work Windows, with the MinGWSys version of Git, and the Cygwin version as well, where standard shell aliases wouldn't work.

You can find out what you do most frequently in Git by setting up this alias:

git config alias.freq 'history | cut -c 8- | grep git | sort | uniq -c  | sort -n -r | head -n 5'

Running git freq will show you your 5 most frequent git commands, which you might like to consider for creating aliases in the future.


Come back next week for another instalment in the Git Tip of the Week series.