Create And Change To A New Directory In One Command

Linux/Mac/Cygwin: Creating folders from the terminal and then switching to them can be tedious, especially when the folder names have spaces, but the One Thing Well weblog writes up a simple trick that makes the process simpler.

Rather than create a folder with one command, and then switch to it with another command, the One Thing Well weblog suggests making an alias that automates the process with a single command. To make the trick even better, however, they show how to make it accept spaces in the folder name, and create full paths in a single step. To create this for yourself, add the following code to your ~/.bashrc file:

# mkdir, cd into it
mkcd () {
mkdir -p “$*”
cd “$*”
}

Once you’ve done so, and either restarted the terminal or just pasted the same code into your active terminal, you can create folders or even folder hierarchies with a single step, like so:

mkcd New Folder/New Subfolder

The trick to making the command work is the $* segment of the function, which expands all arguments and puts them between the quotes. You can use the same technique in any bash function to pass all arguments — for instance, if you wanted to make an improved mkdir command.

mkcd Improved [One Thing Well]

Discuss

(1 Comment)
  • [–]

    Roger Barnes

    Tuesday, May 11, 2010 at 9:54 AM

    Beware if copy and pasting from the blog post. The quotes have been translated to “smart” ones that won’t work in your shell.

Join The Discussion