If you’ve used bash (or any shell) for long you’ve likely run across aliases or functions. They are useful built-in mechanisms. They can be used to write resuable scripts or save keystrokes by shortening your favorite combination of parameters for a command. They work really well, but have a major pitfall - they are built-in. While being “built-in” might not seem that bad, it is restrictive enough that I think they should be avoided when possible. Preferring scripts over shell aliases and functions grants higher flexibility with your tools.
There is nothing inherently wrong with aliases or functions, but
there are places they can’t go. Let’s say you like the alias
git. It saves you two keystrokes and when you use git
on the command line it is what your fingers type. Today you
want to add a shortcut that you can run globally in your OS
that updates a specific git repository. You test it out in your
$ g pull /path/to/my/repo
g is a bash alias then you need to translate
before you can use it in your keyboard shortcut, because
your desktop environment isn’t bash. However, if
g is a script
in your path is a passthrough to
git then you can use the
above command as-is, anywhere on your operating system and
in any program (sudo, vim, an IDE, etc). Using scripts
makes your aliases and functions available globally on your computer,
which means you don’t have to care about where you are executing
a command. It is the same everywhere.
Beyond availability there is another benefit to using scripts -
they are contained in a file. From a code perspective it is better to
have one responsibility per file, which scripts enable. Sharing
a script with someone else is easy – you just have to copy the file
(instead of searching through a large
.bashrc for the right code snippet).
Files are a nice breaking encapsulation of an idea, so I think this is
a big win for scripts.
I would like to say that you should only rely on scripts for everything, but
there are some special cases where scripts just don’t cut it. These primarily
revolve around dynamic evaluation of commands and shell specific state such
as which directory you’re in (you can’t use
cd in a script).
I switched nearly all of my bash / zsh aliases and functions over to scripts a couple of months back and I couldn’t be happier. I think it is the better way of doing things and would encourage you to try it! Thanks for listening to my ideas.