This is something I do frequently

$ mkdir foo
$ cd foo

This works as a single command, but it's more keystrokes and saves no time.

$ mkdir foo && cd foo

Is there a shortcut for this?

Edit

With the use of help below, this seems to be the most elegant answer.

# ~/.bashrc
function mkcd {
  if [ ! -n "$1" ]; then
    echo "Enter a directory name"
  elif [ -d $1 ]; then
    echo "\`$1' already exists"
  else
    mkdir $1 && cd $1
  fi
}
link|improve this question

78% accept rate
You can rename the function to mkdir if you use command mkdir $1 instead of just mkdir $1 in the function body. – Andy Jun 15 '10 at 14:50
(1) why not simply "mkdir $1 ; cd $1" instead of "&&"? that way the "cd" succeeds even if the "mkdir" fails, and you don't need the does-it-already-exist scaffolding. (2) as written your function won't work (to prompt you for a directory name). you need to put that in a separate "if" clause from the existence test (currently in "elif"). – quack quixote Jun 15 '10 at 16:25
feedback

4 Answers

up vote 3 down vote accepted

You can try something like this:

#!/bin/sh
mkdir $1 && cd $1

Save this script to some place that is in your path, for example, /usr/local/bin or ~/bin (you have to put this last one into your path in your ~/.profile file). Then you can simply call it.

link|improve this answer
feedback

I'm no Linux/bash expert, but try putting this in your .bashrc.

function mkdir
{
  command mkdir $1 && cd $1
}

PS Thanks to Dennis for using command mkdir.

link|improve this answer
Instead of `which mkdir`, just use command mkdir. – Dennis Williamson Jun 15 '10 at 14:33
Thanks Dennis. There's nothing under man command - could you direct me to a reference? (I can work out what it does, but it pays to be thorough;) – Andy Jun 15 '10 at 14:49
command is described in the manual of bash (which it is a built-in of; it's not a separate command). You could also try help command. – grawity Jun 15 '10 at 18:39
@grawity Perfect, thanks. – Andy Jun 16 '10 at 8:04
feedback

If you don't want another function, to remember:

$ mkdir /home/foo/doc/bar && cd $_
link|improve this answer
feedback

What about:

$ mkdir newdirname; cd $_

It's a bit easier than using &&, combining quack quixote's and kzh's answers.

link|improve this answer
1  
The point of && is that cd will not be executed if the mkdir command fails – slhck Mar 14 at 9:29
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.