Variables in Bash Alias

Dec 19, 2020 min read

I’m a firm believer that we only have so many keys strokes in our lifetime, I save as many as I can with bash aliases. A simple bash alias can improve your efficiency at the keyboard many times over.

Using variables in your bash aliases helps to pass a value into your alias at specified locations and reuse the value many times. Ya know, like variables do.

Here’s an example bash alias that I like to create a (nested) directory AND cd into that directory:

alias mkdir='_mkdir() { mkdir -p "$1" && cd "$1" ;}; _mkdir'

The trick is to define a function, here I call it _mkdir, and then exporting that function all as part of the alias. We enclose our variable reference in double quotation marks, “$1”.

To use this alias, in the terminal type: mkdir <folder/with/optional/nesting> and be immediately navigated to your new directory. Of course variables combined with bash aliases have a lot of interesting uses.