Introduction to Git Aliases
Git aliases provide a way to shorten popular git commands. For example, you can use “git co” command in place of “git commit”. In other words, it maps a custom command to a standard GitHub command. Like in the example above, the command “git co” was mapped to “git commit”. The user can use both commands, i.e. the original command and the alias to accomplish the same task.
Types of Git Aliases
A Git alias can be either local or global. A local alias is defined for a particular git repository whereas a global alias can be used in any repository. If you create an alias inside a git repository without the global flag, then the alias will be local by default i.e. it can be used in the current repository only. Alias created with global flags can be used in any git repository.
How to create an alias in git?
An alias is created by using the following syntax:
git config –global alias.<custom_command_name> <original_command Name>
$ git config --global alias.co checkout $ git config --global alias.br branch $ git config --global alias.ci commit $ git config --global alias.st status
Here aliases co, br, ci, and st were created globally for the commands checkout, branch, commit, and status respectively.
If the tag “–global” isn’t used then the aliases will be local by default.
Aliases can also be created by editing the .gitconfig files manually. A global alias is stored in the global .gitconfig file which is available under the user home directory in Linux, for a local alias it is inside the .git folder within the repository, or you can say “/.git/config” is the relative path for the file.
The contents of the config file are as shown below. The file contains various information like user email, name, alias, etc. After creating aliases they will be listed under the alias header. One can insert aliases under the [alias] header manually.
Let us take an example to understand how git aliases work. Let’s say we have a repository Power-Puff-Girls, having 3 branches.
So here we’ve used the command “git br” which works the same as “git branch” command listing the branch present in the repository. Note that we can still use the “git branch” command as shown below:
Aliases can also be used to create a new command from a sequence of git commands.
git config --global alias.unstage 'reset HEAD --'
Here we have combined reset and HEAD command to create a new git command.
Both the commands, “git unstage app.css” and “git reset HEAD — app.css” are equivalent.
Benefits of using Git Aliases
- Git aliases can make you a faster and more efficient developer as it can save you a lot of keystrokes in the long run. For example, git commit is a frequently used command, using git ci every time instead of git commit is going to save a few keystrokes.
- It makes the command look simpler and clearer.