Last Updated: September 09, 2019
·
2.961K
· shrayas

A quicker Mkdir

I know that if i'm creating a folder, i need to cd into it in the next command, so i use this shell function instead

function md() {
  mkdir $1 && cd $1
}  

17 Responses
Add your response

An alternative not so short but without altering your environment:

$ mkdir foo; cd !$
over 1 year ago ·

Oh wow. I didn't know about this !$ thanks !

over 1 year ago ·

Look at the following conversation for further informations about the ! operator:
https://coderwall.com/p/lc8h3q?&p=1&q=

over 1 year ago ·

Superb. Thank you

over 1 year ago ·

I use !$ also but I'd suggest && rather than ; because if the mkdir fails (exits with non 0) the cd will still execute.

over 1 year ago ·

Great tip. Here's what I've always used:

function mkcd { mkdir -pv "$1" && cd "$1"; }
function mkgit { mkcd "$1" && git init; }
over 1 year ago ·

@xtagon: I love the mkgit function! Will add it into my dotfiles, thanks ! :)

over 1 year ago ·

Great tip! Thanx =)
What about combining solutions @xtagon & @shrayas:

function mkgit() {
mkdir $1 && cd $1 && git init
}

over 1 year ago ·
over 1 year ago ·

@wimnorder, my version of mkgit calls my mkcd function, so it will create the folder for you as well as cding and initializing git :)

over 1 year ago ·

@xtagon Oh yeaaah! Missed out on that !

over 1 year ago ·

I use this:

mkcd () { mkdir -pv "$@" && cd "$1" }

Supports creating a bunch of directories (and then change to first of them).

over 1 year ago ·

Here's a version I've been using with fish shell - http://fishshell.com/.

function newdir
  mkdir $argv
  cd $argv
end
over 1 year ago ·

Note that ; can actually be better for quick use than &&. With &&, the entire command will fail if the directory already exists. With ;, it will warn you, but still cd into it.

I prefer the latter's "cd in X, making it if necessary" behaviour. YMMV.

over 1 year ago ·

fishshell looks very interesting, @bradgreens

over 1 year ago ·

Why does my zsh hate this, and not cd into the folder?

over 1 year ago ·

I'm accustomed to "take" alias provided by oh-my-zsh

over 1 year ago ·