Wednesday, May 25, 2011

mkdir and cd to created directory with a single command - 11.04 Natty

Not a fan of having to cd to the directory you just created? You likely created it for a reason and 8 times out of 10 not need to cd to it immediately anyway. So, you do this:
user@machine:~$ mkdir -p /dir/needed/to/cd/to/immediately
user@machine:~$ cd /dir/needed/to/cd/to/immediately
user@machine:~$ pwd
/home/user/dir/needed/to/cd/to/immediately

Quick functional solution: Open ~/.bashrc (or .bash_profile) and add the following line:

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

NOTE: You can name this function whatever you like, mkdircd just makes sense to me...

Source ~/.bashrc and now let's do this the easy way:

user@machine:~$ mkdircd dir/needed/to/go/to/immediately
user@machine:~/dir/needed/to/go/to/immediately$ pwd
/home/user/dir/needed/to/go/to/immediately

~Fin

No comments:

Post a Comment