mkcd

How often do you make a directory and then cd into it? You have to type the whole directory twice, which seems redundant.

    mkdir -p this/is/a/long/directory/name
    cd this/is/a/long/directory/name

Even with a good history facility and command line editing facility, like those in BASH, you do a lot of repeating. What if you could simply do this:

    mkcd this/is/a/long/directory/name

Here's a short script to create the function and add it to your session. It's written for BASH, but should be readily adaptable to most shells. And besides, it will teach you some sneaky tricks about shell scripting. The file name is, oddly enough, mkcd.

# -*- shell-script -*-
# mkcd: a script which declares a function, mkcd.

# Time-stamp: <2002-09-03 13:27:08 root mkcd>

# mkcd creates a directory hierarchy, then cds into it all in one
# swell foop. To use it in your shell, run it as:

# . /path/mkcd

# That will execute it without launching a new shell, so that it
# changes your current shell's environment.

# You can then use the function in scripts or from the terminal to
# create a new directory or directory hierarchy, and cd into it. E.g:

# mkcd foo/bar/baz

function mkcd
{
    dir=$1;
    mkdir -p "$dir" && cd "$dir";
}

The guts of it are the function mkcd. It takes the name of a directory, creates it, and then (if the creation was successful) changes directory into it. The -p option to mkdir tells mkdir to create parent directories if necessary, so you can create directories anywhere. Like a lot of Unix tools, it assumes you know what you are doing. (Should you accidentally create a mess of directories you didn't really want, rm -r is your friend.)

As you probably know, when you execute a script by simply calling it, it creates its own environment, executes in that environment, and then goes away. Normally, any changes to the script's environment go away when it ends, and the calling shell's environment is unchanged. So, for example, you can customize $PATH for a script without having to remember the old path and restoring it later.

So if you just execute the script mkcd, it will create the nice function, and then exit. The function will cease to exist when the script exits. This is not very useful. To make the script a permanent part of your environment, call it with a leading dot, like so:

$ . /path/mkcd

In fact, BASH users can make it permanent for an individual user by adding that line to ~/.bash_profile, ~/.bash_login, or ~/.profile, as appropriate. To make it permanent for all users, add it to /etc/profile.

This was originally published Sat Aug 29 15:11:15 MDT 2009.

Update, 2010-10-07: I modified the script to allow directories with spaces in the names (yucch). The idea came from another implementation by One Thing Well.

blogroll

social