Aliases

Author

Alex Razoumov

Sometimes, you want to replace longer Git commands with a shorter version. For example, wouldn’t it be nice if instead of typing git status you could type git st? It turns out this is easy to do via Git aliases – all you need to do is run the following command:

git config --global alias.st 'status'

This will create a Git alias (new Git command) st that will run status underneath.

Of course, this becomes very useful with longer commands, e.g.

git config --global alias.last 'diff HEAD~1 HEAD'
git last

will show the file changes in the last commit, i.e. underneath git last will run git diff HEAD~1 HEAD.

All these definitions are stored in your ~/.gitconfig file, and you can always check them with (pay attention to the alias section in the output):

git config --list

Consider the following useful aliases:

git config --global alias.list 'ls-tree --full-tree -r HEAD'
git config --global alias.one "log --graph --date-order --date=short --pretty=format:'%C(cyan)%h %C(yellow)%ar %C(auto)%s%+b %C(green)%ae'"

Now try running:

git list   # list all files inside the repository
git one    # very nicely formatted version of git log

Now, let’s build an alias for a more complex command: git grep "test" $(git rev-list --all). This example from the “Searching a Git project” section below will search for the string “test” in all previous commits. There are two problems with this command: (1) it takes an argument (the string “test”), and (2) it uses an output from another Unix command (git rev-list --all) as its input.

It turns out you can still automate this with a Git alias stored as a bash script! You need to place an executable bash script into a directory that is listed in your $PATH environment variable. For example, let’s assume that $HOME/bin is listed in your $PATH. Doing the following

cat << EOF > $HOME/bin/git-search
#!/bin/bash
git grep \${1} \$(git rev-list --all)
EOF
chmod u+x $HOME/bin/git-search

will place the script into the file $HOME/bin/git-search and will make it executable. Now, running

git search test

should search the entire current Git project history for “test”.