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
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:
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:
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:
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
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).