> /dev/null

Interesting hacks, snippets, and shortcuts.

Mar 21

Working with multiple items on the $PATH

If you're like me then you have a $HOME/bin directory or something similar where you put custom versions of programs you use. But what if you need the original version for something? Memorizing the path works but is a real pain. Here is how to create a bash function that will run the old version of your command.

The which command

You probably know to use which to get the location of a program on the $PATH, but which can also take in the flag -a to list locations of all occurrences of a program on the $PATH.

Grab the second of the list

To get the second item in a list with bash just use the head and tail commands together:

head -n 2 takes the top 2 items in the list and then tail -n 1 takes the last of those. You can actually grab any index by replacing the 2 with the line you want.

Tying it all together

The easiest way to use this is to add a function to your .bashrc as follows.

I didn't mention shift above. It is simply a bash command that removes the first argument from the argument list. That way you can pass the program $@ and it wont include the name of the program as an argument.

Using your new function

Just type old before the command you would normally use. For example:

$ old vim file.txt

An interesting sidenote, tab completion still seems to work when using this trick. I have no idea why but I'm glad it does.