Terminal: a better way to navigate using ad

By Zach Dennis on 28 Feb 2009

Over the years I've used my own aliases in .profile (or .bashrc) as well as bash functions, perl scripts, etc produced by coworkers or random people on the internet to allow me to more easily navigate to a directory. At its heart the most basic way is a simple bash alias:

alias somedir='cd somedir'

While this works it requires me to open up my .profile or .bashrc file in an editor, find where I place aliases, add the alias, save the file, and source it so I have access to it. If you want to change an alias you have to essentially follow the exact same steps. Way too much manual work regardless of the tools being used. The workflow should be one step: tell your terminal you want an alias. And then it should just work. Overwriting an alias should simply be one step as well: tell your terminal you want an alias.

The result of this desire is a bash function and a ruby script: ad and aliasdir.rb. Together, these two things give you a one-step workflow for aliasing directories. They are a little win against effort and redundancy in the name of simplicity and just-working-ness. Yes, ness.

Using ad

# navigate to some directory
cd projects/opensource/webrat

# tell ad to store an alias to this directory
ad webrat

# now anytime you want to navigate to webrat just
# type the alias name
webrat

# now open a new shell, you have the alias available
# to you
webrat

How it works

ad is a bash function that wraps aliasdir.rb. You invoke this in terminal and it will set up the alias in your current session, and it will use aliasdir.rb to store it. When you open a new terminal session it will just be available.

aliasdir.rb is a ruby script that stores aliases for changing directories. It’s used by ad and you don’t need to interact with yourself, although you can if you want; see aliasdir.rb -h.

Installing

ad and aliasdir.rb are stored on github in MHS’s tidbits project. Clone and create a symlink:

git clone git://github.com/mhs/tidbits.git
ln -s /path/to/tidbits ~/.tidbits

Lastly, copy the ad function below into your .profile, .bashrc, or whatever file is appropriate:

# ad is for *alias directory*. It creates persistent
# aliases. Type 'ad -h' for help.
function ad
{
  ~/.tidbits/lib/aliasdir.rb $@
  eval `~/.tidbits/lib/aliasdir.rb --dump`
}
eval `~/.tidbits/lib/aliasdir.rb --dump

You will need to source the file to make the ad function available to you or you will need to open a new terminal session. This is a one time thing.

Enjoy using ad.