More useful shell aliases

Mike Solomon

Shell aliases

Most developers who spend time in their terminal use at least simple shell aliases. Some, such as alias ll="ls -l" can make common commands much faster. Aliases are very simple but also very limited, so I have found myself using shell functions instead for their flexibility.

Functions instead of aliases

Shell functions in Bash and Zsh allow more than one awkward line of commands, which can be very helpful.

For example, I have a function that pulls my current git branch from the corresponding remote branch on origin. This can be accomplished in an alias, but I would also like to print out the command I am executing to help prevent mistakes, especially if I’m not on the branch I expect to be on:

alias gcurrbranch='git rev-parse --abbrev-ref HEAD'

function gpull() {
    echo "git pull origin $(gcurrbranch)"
    git pull origin $(gcurrbranch)
}

You can see that I use both an alias and a function to accomplish what I want. There is some duplication that would be nice to get rid of and it would be great to have a general way to print what I am executing without that duplication.

Pretty-print and ‘eval’

The most obvious thing to print to the terminal is a string. Bash and Zsh let you use eval to execute a string (this is dangerous if you eval user data in your commands, including file names and contents–please be aware of the security risk).

First let’s try out a using a string for our command:

alias gcurrbranch='git rev-parse --abbrev-ref HEAD'

function gpull() {
    command="git pull origin $(gcurrbranch)"
    echo "${command}"
    eval "${command}"
}

That’s a bit better, but we can extract the print-and-eval logic into a separate function. While we’re doing that, let’s make it print in white so it’s easily distinguishable:

function print_and_eval() {
    echo "\e[0;37m$1\e[0m"
    eval $1
}

alias gcurrbranch='git rev-parse --abbrev-ref HEAD'

function gpull() { print_and_eval "git pull origin $(gcurrbranch)" }

Command-R to Control-L configuration

Now we have commands that print in white and we’ve removed the duplication!

There are some drawbacks to this approach. There are security concerns, we lose syntax highlighting for the commands in the editor, and the printing is imprecise with non-printable escapes (such as in certain sed commands).

Even so, I find this very useful for my git aliases (among others). But please, be careful and do not use commands that could execute user data (including file names).