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.

This entry was posted in shell and tagged , . Bookmark the permalink.

4 Responses to Changing Directories Quickly

  1. Mayhem says:

    Very nice command — I’ll have to use it in my bash scripts.

  2. Christoph says:

    I usually use built-in bash facilities for this:

    “cd !:$” will do the same (and !:$ ist just Shift-1.4 on a German keyboard, not as weird to type as it looks :-) !:$ meaning the last word of the previous line, also works with !:0, !:1, !:2 etc.

    You can also use “cd “. Meta-. cycles through the respective last words of the lines in your history.

    • Christoph says:

      Whoops, WordPress ate some special characters in my last command. The command in the last sentence is meant to be “cd M-.”, where M-. is pressing Meta and the dot “.”.

    • mafr says:

      I knew the Meta-. shortcut, but not back then when I wrote the “g” function, to be honest :)

      There are a few reasons why I still prefer “g”: a) I can’t get the Meta-. shortcut working in vi mode. b) “g” is very short to type and creating an alias for “cd !:$” doesn’t work. c) “g” also changes into extracted tarballs and the like.

      I might switch back to emacs mode soon, but b) is currently a show stopper for me. You don’t happen to have an idea how to solve this? I’m always happy to throw away unneeded code ;-)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s