Shell timesaver: mkdir and cd combined

📄 wiki page | 🕑 Last updated: Sep 11, 2022

Often when you create a new directory, you want to also cd into it:

mkdir mydir
cd mydir

This is a very handy function I'm using for this purpose:

function mcd() {
  mkdir -p "$1"
  cd "$_"

You can just put it into your ~/.bashrc (or ~/.zshrc) file, and it will be automatically included when you open a new shell.

Now you can do something like this:

mcd mydir/subdir

And both directories will be created and you current directory will change to mydir/subdir.


We're defining a function called mcd, which is doing the following:

mkdir -p "$1"

$1 contains the first passed argument to the function (directory names containing spaces need to be quoted, or you can use [email protected] to get all arguments, with included spaces).

mkdir -p recursively creates directory based on that argument (that means that, besides doing mcd mydir, we can also do something like mcd mydir/subdir).

cd "$_"

$_ holds the last argument of the previous command (directory name in our case), and we're just cd-ing into it.

Comments and suggestions

You can use this form to submit a suggestion or a comment.

If you find this site useful, please consider supporting it. Supporters also get access to some extras.