Last Updated: December 14, 2016
·
5.026K
· jwebcat

mkdircd the child of mkdir and cd

How often do you find your self typing this?

$ mkdir dirName && cd dirName
  • Here is an function you can pop in your .bashrc or .bashprofile
function mkdircd () { mkdir -p "$@" && cd "$@"; }
  • In the above passing the - p flag to mkdir will also create all directories leading up to the given directory that do not exist already. If the given directory already exists, to ignore the error. from The wiki on mkdir .

  • then the $@ tells mkdir to use the first argument passed to the function . In this case the dirName or the filetree that you input to the command mkdircd .

  • After that && tells bash to execute the second command only if the first executes successfully.

  • then we pass the same $@ to cd so that it uses the first argument passed to the function as well.

  • I hope you enjoy your new mkdircd function. You can call it whatever you want ant invoke it from bash like

$ mkdircd coolStuff
$ pwd
$ /coolstuff

pretty nifty eh?

If your not into masking a .bashrcetc. or you just want a portable version here it is.

$ mkdir /path/to/your/newstuff && cd $_
  • In the above we pass $_ to cd . $_ is the most recent parameter (or the abs path of the command to start the current shell immediately after startup). or the last argument of last command in this case. More info about that here

For ksh and zsh users I got Love for you too

  • Here are two aliases that do the same thing, I found here on stack overflow for ksh and csh that I haven't tested because I don't use those shells.

  • I would Love some feedback on them as I would like to know if they are efficient etc.

  • for csh

alias mkcd 'mkdir \!^; cd \!^1'
  • for ksh
alias mkcd='_(){ mkdir $1; cd $1; }; _'
  • Enjoy

2 Responses
Add your response

Actually, the "$@" in the bash function stands for "all arguments to this function, quoted" (the first argument would be "$1"). Running "mkdircd a b" would create two directories, and then cd into the first.

over 1 year ago ·

Yes that's exactly what I said.
Below is quoted from my protip above.

then we pass the same $@ to cd so that it uses the first argument passed to the function as well.

then the $@ tells mkdir to use the first argument passed to the function . In this case the dirName or the filetree that you input to the command mkdircd

Passing a second argument to this alias is not the point of this command.

Thanks for pointing that out though :P

over 1 year ago ·