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.

Explanation

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 $@ 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.


Ask me anything / Suggestions

If you have any suggestions or questions (related to this or any other topic), feel free to contact me. ℹī¸


If you find this site useful in any way, please consider supporting it.