Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 78 ยท Customizing and Automating Git

Aliases and Everyday Productivity

Create Git aliases and shell aliases, build custom git subcommands, and set the config options that remove daily friction: rerere, autostash, pull.rebase and more.

Git has a lot of commands and even more options, and you type the same handful of them hundreds of times a week. A little customization pays off quickly: shorter commands, a readable log, safer defaults, and settings that quietly remove whole classes of annoyance (like resolving the same conflict twice). Nothing in this lesson changes how Git stores your data. It only changes how comfortable it is to use.

You will learn the three kinds of shortcut (Git aliases, shell aliases and your own git-something programs), a set of aliases worth stealing, and the configuration options experienced users turn on first. Everything is stored in the config files from Installing and Configuring Git; in our sandbox each example writes to a throwaway ~/.gitconfig, so nothing leaks between runs.

Git aliases

An alias is a config entry under alias.<name> whose value is a Git command line, without the leading git. You create it with git config and then run it like a built-in command.

Bash Create and use Git aliases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Aliases are stored in the [alias] section of whichever config file you wrote them to: --global means ~/.gitconfig (all your repositories), no flag means the current repository only. You can also edit the file by hand, which is handy for long aliases.

INI
[alias]
    st = status --short --branch
    co = checkout
    sw = switch
    ci = commit

Two rules to know:

  1. An alias cannot override a real Git command: alias.status is ignored. Pick a new name.
  2. Extra arguments are appended: with alias.st = status -sb, running git st src/ runs git status -sb src/.

Aliases that run shell commands

If the value starts with an exclamation mark, Git runs it in a shell, from the top directory of the repository. That lets an alias use pipes, several commands and non-Git tools. Arguments are appended to the end of the line, so when you need them in the middle, wrap the body in a small shell function:

INI
[alias]
    # last five branches you checked out, most recent first (note the shell function)
    recent = "!f() { git reflog | grep -o 'checkout: moving from .* to .*' | head -n \"${1:-5}\"; }; f"
Bash Shell aliases with arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

git undo is one of the most useful aliases there is: it removes the last commit but keeps its changes staged, ready to be recommitted (reset in depth explains why --soft does that). Because shell aliases run from the repository root, relative paths inside them refer to the root even if you invoked them from a subfolder. If you need the original directory, use the environment variable GIT_PREFIX.

A set worth stealing

The best aliases wrap commands you already use. Here is a starter set. Add what fits your habits and delete the rest.

INI
[alias]
    st      = status --short --branch
    lg      = log --graph --abbrev-commit --decorate --format='%C(auto)%h%d %s %C(dim)(%an, %ar)%C(reset)'
    lga     = lg --all
    last    = log -1 --stat
    unstage = restore --staged
    undo    = reset --soft HEAD~1
    amend   = commit --amend --no-edit
    wip     = !git add -A && git commit -m 'WIP'
    fixup   = commit --fixup
    cleanup = !git branch --merged | grep -v -E '^(\\*|\\s*(main|master|develop)\\s*$)' | xargs -r git branch -d
    pushf   = push --force-with-lease
    root    = rev-parse --show-toplevel

A few notes: lg is a one-line graph that shows branches and tags; pushf replaces the dangerous --force with the lease version (push and pull); cleanup deletes local branches already merged into the current one (Branch Management); fixup pairs with the --autosquash option of interactive rebase. Aliases that chain another alias (lga = lg --all) work.

Bash A readable one-line log alias

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

In real life you would add colors with %C(auto) or %C(yellow) and a relative date %ar; they are left out here only to keep this output plain and the same on every run. The --format placeholders are listed in Viewing History.

Shell aliases are a separate thing

Do not confuse Git aliases with shell aliases from your .bashrc or .zshrc. A shell alias shortens what you type before Git even starts, for example:

Terminal
alias g='git'
alias gs='git status -sb'
alias gl='git lg'
alias gco='git checkout'

(This block is read-only: our sandbox does not keep shell startup files between runs.) The two layers combine: gl expands in the shell to git lg, which Git then expands to the long log command. A shell alias like g has one drawback: tab completion for g checkout <branch> only works if you tell the completion system that g behaves like git; in Bash that is complete -o default -o nospace -F __git_main g after loading Git's completion script. Many frameworks (Oh My Zsh's git plugin, for instance) ship a long list of such shell aliases, which are worth skimming even if you never use them all.

Your own subcommands

When Git sees git foo and foo is neither a built-in nor an alias, it looks for an executable called git-foo on your PATH and runs it with the remaining arguments. This is how git lfs and git flow work. It is the right tool when an alias would be too long or you want a proper script with error handling.

Bash A custom subcommand: git-branches-by-age

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The script ran as a subcommand and printed branches with the most recent commit first. A script can be written in any language. Name it git-<name> with dashes, make it executable, and put it in a directory on your PATH (many people use ~/bin).

Settings that remove friction

Aliases save keystrokes; these options save thinking. Each is one git config --global line. They are listed roughly by how many people benefit.

Setting Effect
init.defaultBranch main New repositories start on main
pull.rebase true (or pull.ff only) git pull rebases (or refuses to create merge commits) instead of making accidental merges (push and pull)
push.autoSetupRemote true First git push sets the upstream automatically; no more "has no upstream branch"
fetch.prune true git fetch deletes remote-tracking branches that no longer exist on the server
rebase.autoStash true git rebase and git pull --rebase stash and restore uncommitted changes for you
rebase.autoSquash true git rebase -i arranges fixup! commits automatically
merge.conflictStyle zdiff3 Conflict markers include the base version; see merge internals
diff.algorithm histogram Usually better-looking diffs
diff.colorMoved default Moved code blocks are coloured differently from changed ones
rerere.enabled true Git remembers how you resolved a conflict and reuses it
help.autocorrect prompt A mistyped command offers the correct one (git stauts becomes a question)
core.excludesFile ~/.gitignore_global Editor and OS files ignored everywhere (ignore rules)
branch.sort -committerdate git branch lists the most recently used branch first
column.ui auto git branch and git status use columns on wide terminals
commit.verbose true The commit message editor shows the diff you are committing

Check the value that actually applies, and where it came from, with git config --show-origin --get <name>. A one-off setting for a single command uses -c: git -c diff.algorithm=patience diff.

Bash A global config file and --show-origin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

rerere: reuse recorded resolution

rerere stands for "reuse recorded resolution". Once enabled, Git remembers the preimage of each conflict and the resolution you committed. When the same conflict shows up again, which happens constantly when you rebase a long branch several times or re-merge after an abort, Git applies your earlier fix automatically. It is also what makes it cheap to try a merge, abort it, and later redo it.

Bash rerere resolves the same conflict a second time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The second merge still reports the conflict, but rerere says Resolved 'style.txt' using previous resolution and writes your teal answer into the file. You only need to git add it. Review the result before committing; rerere trusts that the same conflict deserves the same fix.

The recorded resolutions live in .git/rr-cache. git rerere forget <path> removes a resolution you now think was wrong, and git rerere status lists the files rerere is tracking right now.

Seeing more in your prompt and terminal

Most of the remaining quality-of-life features belong to the terminal rather than to Git, so they are read-only here:

  • Tab completion. Git ships git-completion.bash and git-completion.zsh scripts (the Windows installer and most Linux packages enable them). They complete commands, branches, tags, remotes and even your aliases.
  • A branch in the prompt. git-prompt.sh provides __git_ps1, which prints the current branch and a status symbol (* changed, + staged, % untracked) in your shell prompt. Set GIT_PS1_SHOWDIRTYSTATE=1 to turn on the symbols. Frameworks like Starship and Oh My Posh offer the same with themes.
  • A pager. Git pipes long output to less by default (core.pager). A better diff viewer such as delta or diff-so-fancy can replace it: git config --global core.pager delta. In scripts and in our sandbox the pager is switched off.
  • Colour. color.ui auto (the default today) colours output only on a terminal. The next example shows the escape sequences Git emits when colour is forced.
Bash Forcing colour: what the terminal receives

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

^[[31m starts red text and ^[[m resets it. Configuration keys such as color.diff.new, color.status.changed and color.branch.current let you restyle each part of the output.

Habits worth adopting

  • Name aliases for what you do, not for the command they hide. undo, amend and unstage document themselves.
  • Keep aliases safe. An alias called force-everything that runs reset --hard is a trap. Prefer the lease form of force push and aliases that keep changes (reset --soft).
  • Share good defaults with the team through documentation, not through a shared .gitconfig: personal config belongs to a person. A repository can offer settings in an include.path file or a setup script; see includeIf in Installing and Configuring Git.
  • Remember that aliases hide the real command. Before you teach a colleague or debug a problem, know what the alias expands to (git config --get alias.name).
  • Learn the long form first. Aliases are a reward for understanding a command, not a substitute.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you create a Git alias so that 'git co' means 'git checkout' in all your repositories?

    Aliases are config values under alias.<name>. Using --global stores them in ~/.gitconfig so they apply everywhere.
  2. 2. What does a leading exclamation mark mean in an alias value, such as alias.who = '!git shortlog -sn'?

    A ! prefix runs the alias in a shell from the repository root, so it can use pipes, several commands and non-Git programs.
  3. 3. You create an executable file git-cleanup in a directory on your PATH. What happens when you run 'git cleanup'?

    When a command is not built in and not an alias, Git looks for git-<name> on PATH and runs it. That is how git lfs and git flow work.
  4. 4. What does the rerere setting do?

    rerere = 'reuse recorded resolution'. It is saved in .git/rr-cache and applied automatically on a matching conflict; you still stage and commit the result.
  5. 5. Which alias is the safest replacement for typing 'git push --force'?

    --force-with-lease overwrites the remote branch only if it still has the commit you last saw, so you cannot silently destroy a colleague's new work.

Summary

  • A Git alias is alias.<name> in a config file; --global makes it available everywhere. It cannot replace a built-in command, and extra arguments are appended.
  • A leading ! runs an alias as a shell command from the repository root; wrap it in a function to place arguments in the middle.
  • Any executable git-<name> on your PATH becomes a subcommand git <name>.
  • Handy aliases: st, lg, undo, unstage, amend, fixup, pushf (with --force-with-lease), cleanup.
  • Settings that remove friction: pull.rebase, push.autoSetupRemote, fetch.prune, rebase.autoStash, merge.conflictStyle zdiff3, diff.algorithm histogram, rerere.enabled, help.autocorrect.
  • git config --show-origin tells where a value comes from; git -c key=value overrides it for one command.
  • Shell aliases, completion, prompts and pagers are terminal features that complement Git's own settings.

Next: Git Hooks