Falvotech.
Conquering the world is easy — what do you do with it afterwards?

L I N K S


⇐ Unit Tests Enhance Code Familiarity

⇒ Unsuitable in Unsuitable: Foreward


Quick Bash Tip: Environment Variables as Aliases
Samuel A. Falvo II
kc5tja -at- arrl.net
2010 Jun 25 11:04 PDT

I miss AmigaOS's ASSIGN command and its pseudo-devices which point to a directory of your choice (or, in the case of AmigaOS 2.x and later, multiple directories, thus eliminating the need for special environment variables like PATH). I also miss AmigaOS 2.x's ability to just type a directory name like a command to switch to that directory. Thankfully, I can regain a bit of both semantics using Bash's environment variables and quote expansions.

I discovered long ago that you can synthesize aliases using environment variables. For example,

$ export L='ls -ltr'
$ $L

I use this capability to create a number of directory aliases:

$ cd extremely/long/path/here
$ export D0="cd `pwd`"
$ cd /another/long/path/goes/here
$ export D1="cd `pwd`"

At this point, I can now type in $D0 to jump immediately to .../extremely/long/path/here and $D1 to jump to /another/long/path/goes/here. Nifty!

You might be wondering why I first cd and then assign the environment variable. It's because I never can remember the full long path name, so I use tab completion on the command-line to assist. Or, sometimes, I'll synthesize the path using $(dirname $(find . -type f -iname foo.bar)) or some such. The point isn't how the variables are assigned, it's that they can be assigned and used as commands just like aliases can. And since they're environment variables and not aliases, you can use them in other expansions or change them algorithmically.