Create a directory and change into it at the same time

md () { mkdir -p "$@" && cd "$@"; }
How often do you make a directory (or series of directories) and then change into it to do whatever? 99% of the time that is what I do. This BASH function 'md' will make the directory path then immediately change to the new directory. By using the 'mkdir -p' switch, the intermediate directories are created as well if they do not exist.
Sample Output
abd-pb-2:bin md test
abd-pb-2:test md a/b/c/d/e

By: drewk
2009-09-24 16:09:19

7 Alternatives + Submit Alt

What Others Think

This command does not work if the directory has embedded space: mcd "foo bar" To fix: function md () { mkdir -p "$@" && cd "$@"; }
haivu · 643 weeks and 1 day ago
Thanks! you are correct and I fixed it...
drewk · 643 weeks ago
I would remove the redundant and bash specific "function" keyword. I use this in my .bashrc which I've commented on here:
pixelbeat · 643 weeks ago
Done! I usually like to use "function" because it aids interpreting what a function is. I don't have to notice the parens. But it is BASH specific... Liked your web site.
drewk · 643 weeks ago
You may want to switch the second one to $_ instead of $@ md() { mkdir "$@" && cd "$_"; } That way if you want to add some options to mkdir, such as -p to make parents or -m to set mode, they'll get passed to mkdir without blowing up cd.
splante · 541 weeks and 6 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this? is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.


Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: