This is something I do frequently
$ mkdir foo
$ cd fooThis works as a single command, but it's more keystrokes and saves no time.
$ mkdir foo && cd fooIs 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
} 3 11 Answers
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.
The bash, zsh Shells
If you don't want another function to remember and don't mind bashisms:
$ mkdir /home/foo/doc/bar && cd $_The $_ (dollar underscore) bash command variable contains the most recent parameter. So if a user were to type the following at the command line: echo foo bar && echo $_ baz, then the output would be as follows:
foo bar
bar bazThe fish Shell
In the fish shell, I would type the following:
> mkdir /home/foo/doc/bar > cd alt + ↑
The alt key combined with either the up or the down arrow key will cycle through command parameter history.
5For oh-my-zsh users:$ take 'directory_name'
Reference:
2What about:
$ mkdir newdirname; cd $_It's a bit easier than using &&, combining quack quixote's and kzh's answers.
2You can try something like this:
#!/bin/sh
mkdir $1 && cd $1Save 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.
1$echo 'mkcd() { mkdir -p "$@" && cd "$_"; }' >> ~/.bashrc
$mkcd < pathtofolder/foldername > Here is a simple function I put in my ~/.config/fish/config.fish file which accomplishes this task:
function mkcd mkdir -pv $argv; cd $argv;
endThe -pv tag allows for the creation of directories with sub-directories.
If you use zsh there is a cool shortcut:
take <Your_folder_name>
and it will create a folder and change to it ;)
Depending on the desired outcome if the directory already exists.
Fail if directory already exists
mkcd() { mkdir $1 && cd $1
}Change directory regardless
mkcd() { mkdir $1 ; cd $1
}Usagemkcd some/path/to/my/dir
I found that the function below can only make one directory, if I want to make subdirectories at the same time, it doesn't work :
function mkdir
{ command mkdir $1 && cd $1
}So I changed it and now its working great!
function mkcd
{ command mkdir -pv $1 && cd $1 && echo "Now in `pwd`"
} For bash macos this is the only way it worked for me
function md
{ command mkdir -vp $1 && command cd $1 && echo "Now in `pwd`"
}