Git Beyond the Basics: Getting the Most with Git Aliases
This is part 2 of a 6-part series on Git commands.
Some of the Git command syntax can be described (charitably) as baroque, and it’s unsurprisingly one of the roadblocks that can slow down newbies. Thankfully, Git provides an under-utilized facility to address this known as aliases. A Git alias is not dissimilar from a Bash (or other shell) alias, in that it defines a piece of text as a key that Git will recognize and expand into something else, optionally including arguments in the process.
Providing new developers with a starting .gitconfig file1 can pre-define a variety of useful aliases to save time, provide examples, and standardize commands across teams or the organization as a whole. Aliases can even smooth the transition from other version control systems, insofar as they can provide commands more familiar to users of those systems that produce corollary results in Git.
For example, consider some poor soul migrating to Git from Visual SourceSafe. The command with which he’s familiar is named history. The following Git alias provides a history command with prettier, output to boot:
[alias] history = log --pretty=format:'%C(cyan)%h%Cred%d %Creset%s%Cgreen [%cn]' --decorate
That alias will work out of the box on any ANSI-aware shell. Windows users will need an ANSI-aware alternative such as the open-source Ansicon or JP Software’s TakeCommand because Microsoft does not include support in the default command processor.
You can define the history alias by putting those lines in your
.gitconfig file. You may also define aliases from the command line via the following pattern:
git config --global alias.key 'value'
In the above, key should be replaced with the text that should trigger the alias, whereas the value should be replaced with its expansion text. And note well: some aliases, like the above history example, are easier to define by editing the configuration file due to argument quoting (and other) issues.