Alex Razoumov

Marie-Hélène Burle

You might find it convenient to replace some long Git commands with shorter versions.

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.

Here is the syntax to create a Git alias for all your Git repos:

git config --global 'status'

This creates a new Git command git st that expands to git status.

Of course, this is particularly useful with longer commands.

Here is an example to list all files in a repository:

git config --global alias.list 'ls-tree --full-tree -r HEAD'

To get the list of files, you can now simply run:

git list

Global aliases are stored in your ~/.gitconfig file. You can print them with:

git config --list

You can set aliases for specific repos without the --global flag (although, it is unclear to me why you would ever want to do this).

Here is another example:

git config --global alias.graph \
 "log --graph \
      --date-order \
      --date=short \
      --pretty=format:'%C(cyan)%h %C(yellow)%ar %C(auto)%s%+b %C(green)%ae'"

Now, git graph will give you the log in the form of a compact graph with nice colour-coding.

Here is a more complex example involving an argument and a Unix command:

Imagine that you want to create an alias that allows you to easily run commands such as: git grep "test" $(git rev-list --all).

This searches for the string “test” in all previous commits. This command takes an argument (the string “test”) and it uses the output from another Unix command (git rev-list --all) as its input.

To turn this into an alias, you need to create an executable bash script and place it in your $PATH environment variable:

# Assuming that `$HOME/bin` is listed in your `$PATH`

# Create a Bash script in `$HOME/bin`
cat << EOF > $HOME/bin/git-search
git grep \${1} \$(git rev-list --all)

# Make it executable
chmod u+x $HOME/bin/git-search

You can now run git search test to search the entire Git project history for the string “test”.

Of course, it works with any other string: git search Methods will search for the string “Methods”.