Creating powerful git aliases

Vitaly Belman
2 min readFeb 13, 2015

Multi-line and multi-command

Recently, while trying to improve my work flow, I noted I have several patterns that I would love to capture as a single command.

For example, I had the following common flow:

  • While working on a branch, find out that I have to do work on another branch (due to a PR comment, for example)
  • Check the status of my current work folder
git status
  • Commit my current dirty files as WIP (or throw them away if not needed)
git reset --hard
# OR
git commit -a -m "WIP"
  • Check out the bug branch that requires work
git checkout bug/4123
  • And then, when I am done working, switch back, and possibly restore my WIP commit
git checkout feature/323
# Restore WIP commit if needed
git reset --soft HEAD~1

Since it was a pattern that was repeating constantly, I was looking for a way to turn it into a git alias.

After some initial Bash struggling, I had the following 3 aliases:

  • safereset — A utility alias that checks for dirty files, and allows to the user an option to discard, commit WIP or cancel the operation
  • switch — Uses safereset, then changes a branch. If a WIP commit is found, it is restored.
  • switch-back — Uses switch alias to switch to the last branch that was checked out.

A practical usage of these aliases in a scenario I’ve described above would be:

# A PR comment was posted while I am in middle of feature
git switch bug/4123
# Fix bug
git switch-back

The code is quite simple, though it does has some unpleasant escaping. On the technical level, it allows me to make git aliases, in the future, that:

  • Use Bash functionality in Windows easily
  • Multi-command aliases
  • Multi-line aliases (easier to read/debug)
  • User input
  • Basic error handling via trap

Here is the code itself, ready to be pasted:

--

--