Previous post:

Next post:

Hack 3. Perform mkdir and cd using a single command

by Ramesh

Sometimes when you create a new directory, you may cd to the new directory immediately to perform some work as shown below.

# mkdir -p /tmp/subdir1/subdir2/subdir3

# cd /tmp/subdir1/subdir2/subdir3

# pwd
/tmp/subdir1/subdir2/subdir3

Wouldn’t it be nice to combine both mkdir and cd in a single command? Add the following to the .bash_profile and re-login.

$ vi .bash_profile

function mkdircd () { mkdir -p "$@" && eval cd "\"\$$#\""; }

Now, perform both mkdir and cd at the same time using a single command as shown below:

# mkdircd /tmp/subdir1/subdir2/subdir3

[Note: This creates the directory and cd to it automatically]

# pwd
/tmp/subdir1/subdir2/subdir3
Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Previous post:

Next post:

{ 2 comments… read them below or add one }

1 Smok Wawelski January 14, 2010 at 6:09 am

Why don’t You use
mkdir -p "$@" && cd $_;
instead of
mkdir -p "$@" && eval cd "\"\$$#\"";
? Isn’t it a bit clumsy?

2 Raksi September 12, 2011 at 11:50 pm

>Why don’t You use
>mkdir -p “$@” && cd $_;
>instead of
>mkdir -p “$@” && eval cd “\”\$$#\”";
>? Isn’t it a bit clumsy?

Because it is possible to create directories that contain “space” characters. With your solution it is not possible. Anyway, thanks for the hack.

Leave a Comment

Previous post:

Next post: