Changing Directories Quickly

When you work with the interactive shell, there's a common pattern that is used a lot: Copying or moving files to a directory and then changing to the target directory using cd. In these cases, you find yourself typing the name twice:

$ cp file1 file2 file3 /very/long/path/name
$ cd /very/long/path/name

Tab completion helps, but for long names it's still tedious.

One of my favourite tools, the bash function g ("go"), shortens this to the following:

$ cp file1 file2 file3 /very/long/path/name
$ g

It works by getting the previous command from the bash history, treating the last argument as a directory and then going there. If the last argument is a file name, the g function tries to resolve it to a directory name by using the basename or stripping off common archiver suffixes like tar, tar.gz or zip.

The function is one of the most executed commands in my shell history. I also had a companion function which changed back to the previous directory, but since cd - is pretty short, too, it didn't get used that often. To use it, download the function and simply copy it into your ~/.bashrc file.

Note that this function works on bash only. I used to have a Korn shell compatible function, but it didn't work as nicely as this one.