Elegant Solutions: A Short Cut to Your Files
When you create a new directory in Unix, say a project folder, you will likely find yourself cd
-ing or typing out its relative, or even full, path with other tools often.
If this were a GUI environment you could drag that folder onto the desktop and have quick access to it, GUI-wise. In Unix you could create aliases but that’s unwieldy. Far better obviously to use environmental variables.
It seems patently obvious, but here is a “back-to-front” method that I find so elegant that I can’t stop smiling each time I invoke it. (It’s because it took me over 30 years to figure it out (yeah, I know…), and I know it will save me from many keystrokes in the future).
First, let’s say you are getting ready for a new project. Don’t immediately use mkdir
, instead, set the environmental variable first:
$ export PROJA="$HOME/path/to/my/project"
$ mkdir -p $PROJA && cd $_
Note that there is no trailing /
after “project” so you can use it as the start of a relative path. You define the path once, and this method then abstracts it away. You never have to type the path to that directory ever again!
Well, that is until you invoke a new shell that is not a child of that shell. To make this shortcut persist we have to place it in a config file. In bash, I could place it in .profile
if I mainly work in a login shell (say from ssh
sessions):
$ echo 'export PROJA=$HOME/path/to/my/project' >> ~/.profile
$ source !$ && mkdir -p $PROJA && cd $_
A word on the !$
and $_
expansions. The underscore “_
” is actually a shell parameter holding the last argument of the previous command. Hence $_
will retrieve $PROJA
from mkdir -p $PROJA
.
!$
is known as a word designator for history expansion. That is, it is not a shell parameter but looks through your history and expands, in this case, the last word in history. If you look at the 2 line bash commands above, we cannot use $_
to retrieve ~/.profile
to source
because the last argument of the last command in that line is PROJA.../project
. (Yeah, the >>
redirect is somehow not a command.) So we have to use history instead.