In Chapter 2, Git Fundamentals – Working Locally we already mentioned Git aliases and their purpose; in this paragraph, I will suggest only a few more to help you make things easier.
One thing you can find useful is to shorten common commands like git checkout
and so on; therefore, these are some useful aliases:
$ git config --global alias.co checkout $ git config --global alias.br branch $ git config --global alias.ci commit $ git config --global alias.st status
Another common practice is to shorten a command by adding one or more options that you use all the time; for example set a git cm <commit message>
command shortcut to alias git commit –m <commit message>
:
$ git config --global alias.cm "commit -m"
Another common way to customize the Git experience is to create commands you think should exist, as we did in Chapter 2, Git Fundamentals – Working Locally with the git tree
command.
The classic example is the git unstage
alias:
$ git config --global alias.unstage 'reset HEAD --'
With this alias, you can remove a file from the index in a more meaningful way as compared to the equivalent git reset HEAD <file>
syntax:
$ git unstage myfile.txt $ git reset HEAD myfile.txt
Do you want a fast way to revert the last ongoing commit? Create a git undo
alias:
$ git config --global alias.undo 'reset --soft HEAD~1'
You will be tempted to use the --hard
option instead of the --soft
option, but simply don't do it as it's generally a bad idea to make it too easy to destroy information, and sooner or later, you will regret for deleting something important.
If you want the alias to run external shell commands instead of a Git subcommand, you have to prefix the alias with a !
:
$ git config --global alias.echo !echo
Suppose you are annoyed by the canonical git add <file>
plus git commit <file>
sequence of commands, and you want to do it in a single shot; here you can call the git
command twice in sequence creating this alias:
$ git config --global alias.cm '!git add -A && git commit -m'
With this alias you commit all the files, adding them before, if necessary.
Have you noted that I set again the cm
alias? If you set an already configured alias, the previous alias will be overwritten.
There are also aliases that define and use complex functions or scripts, but I'll leave it to the curiosity of the reader to explore these aliases. If you are looking for inspiration, please take a look at mine at https://github.com/jesuswasrasta/GitEnvironment.
Removing an alias is quite easy; you have to use the --unset
option, specifying the alias to remove. For example, if you want to remove the cm
alias, you have to run:
$ git config --global --unset alias.cm
Note that you have to specify the configuration level with the appropriate option; in this case, we are removing the alias from the user (--global
) level.