Did you know that you can add custom aliases to the
git command? I recently switched to a new Macbook and realised that I was missing some commands that it turns out I was using daily. Manually restoring them showed me two things:
- I need to use sync my
- Git aliases are a huge part of my daily development workflow.
Before you add any aliases, you’ll need a
.gitconfig file in your home directory, (for example,
~/.gitconfig). This file will often already exist to configure the name and email address to make commits with.
[user] name = James Brooks email = [email protected] [core] editor = nano [alias] ; List all branches. branches = branch --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(contents:subject) %(color:green)(%(committerdate:relative)) [%(authorname)]' --sort=-committerdate ; Delete a branch. del = branch -D ; Show the last commit. last = log -1 HEAD --stat ; Undo the last commit. undo = reset HEAD~1 --mixed ; Add and commit everything with "wip" as the commit message. wip = !git add --all && git commit -m 'wip'
As you can see, I don’t actually have a lot of aliases. I’ve tried to keep it simple and only have aliases that I use regularly. I also don’t add aliases to shorten existing commands (without passing options).
To add an alias, we need to append commands to the
[alias] section of our config file. The format is
aliasName = aliasCommand.
You may also add an alias using the
git config command:
$ git config --global alias.undo 'reset HEAD~1 --mixed'
There are a few things to know about when creating Git aliases:
- Aliases can run more than just one command. Take a look at the
wipalias; it calls
git add --alland then
git commit -m 'wip'. You can also call other Git subcommands, such as
- You may’ve noticed that the
undoalias does not call the
wipdoes. For aliases that simply run another Git command but with additional parameters, this is absolutely fine. However, if you want to run a command that is not a Git subcommand (or you're running multiple commands), you should prefix it with
!. This stops Git from trying to run the command as a subcommand.
- Aliases don't need to run a Git subcommand. You could run another application for example,
visual = !gitk.
- You could use an alias to make a shortcut for another command, for example
p = pushso you can now run
You can learn more about how aliases work at the Git Aliases documentation.