raw.githack.com

Git aliases and how to use them Aliases is a helpful git feature that lets you do more typing less. Here we'll find out how to use them.

We will start with a simple statement – the less you do and the more you get – the better. This means that if you can achieve something in three keystrokes instead of nine your performance is 3x higher. Also, if you use an alias, you don’t have to remember syntax for complex commands you may want to use.

So how can you achieve that? The answer is aliases. Basically, nicknames for commands – similar to how you call your friend Nick instead of Nicholas. And we will start with an alias for git command itself! We are going to shorten that long 3-letters thing to just one symbol – g. At first sight this doesn’t seem like a big improvement, just one keystroke instead of three, but it can save you a lot of time at the end of the day.

Just open the config file of your shell of choice (~/.zshrc, ~/.bashrc) and put the following line to it:

alias g='git'

Now reopen your current session and start a new one and – viola! – now you can write g status instead of that long git status! Isn’t that cool? But we are going to improve this even more.

Well, basically, you can now use the same approach to add even more git aliases, i. e. by using your shell aliases. But git has its own alias facilities, built in right into it. They can be either global (placed in global ~/.gitconfig file) or per-repo, which can be useful in some circumstances (say you have to do some routine operation but only in one repo from a dozen).

Okay, let’s jump into it. To create a native git alias, you can either open ~/.gitconfig file and add a new entry under [alias] block (you may have to create the file and the block first) or use git command to manipulate its own config file. For example, let’s create an alias for the status command:

g config --global alias.st status

Type that in, and then do g st in any repo. Whoa! How fast is that?!

I will now provide a list of some aliases I use daily, maybe they will be useful for you too. But don’t just stick to this list – extend it with your own findings!

[alias]
co = checkout             # "g co main" instead of "git checkout main"
cm = commit -v            # "g cm" to commit something
amend = commit --amend    # when you want to add more changes to the current commit
reword = commit --amend   # to change commit message of the last commit you did
undo = reset --soft HEAD^ # to, well, undo the commit (without resetting changes)
df = diff --color-words   # to see inline changes
mg = merge --no-ff        # merge with explicit merge commit

# pretty history viewer with ascii-art branches, merging, etc
hist = log --pretty=format:'%Cred%h%Creset %ad | %Cgreen%s%d%Creset [%an]' --graph --date=short

Happy hacking!