I have moved my blog to Wordpress at theunixgeek.wordpress.com. I will still be checking back periodically on this one as well, though. 19 April 2009


Merging Mkdir and Cd | 280 Slides Interview | I Switched to KDE 4

clickable portals

Saturday, February 21, 2009

Merging mkdir and cd

I oftentimes use mkdir and cd together, as in mkdir project && cd project or mkdir project; cd project and I believe many people probably do the same thing. I always found it tedious and repetitive to have to type in the directory's name twice, so I thought, "why not merge these two into one command?" Something like mkcd project could do both jobs at once and reduce typing; it's like hitting two birds with one stone, so to speak.

The biggest problem I've encountered in the implementation of a seemingly simple idea is that when programs or shell scripts are run they are child processes. That said, you can't have a simple BASH script that reads "mkdir $1 && cd $1" because it would only switch to the directory while running as a child process instead of actually switching to the directory. The same applies to the system( ); function in stdlib.h (in C, C++ - cstdlib -, and related languages).

I am considering submitting the idea to the GNU project. The idea has been sent and I'm awaiting their reply.


Tomy said...

function mkcd()
mkdir $1 && eval cd $1

Simon said...

mkdir $A&& wait && cd $A

The command in the middle "wait" is a shell built-in (i think) that waits for all file io to finish (again i think)

Should be easy enough to alias this to something, or put a cmd in /usr/local/bin

Craig said...

Make a shell script that does the mkdir $1 && cd $1, then make a bash alias like this:

alias mkcd='. /path/to/mkcd'

The . makes it source the file in the current shell rather than forking, and thus works. You can then expand your mkcd script to include options such as -p to make it more useful, which you couldn't do with just a plain alias.

sagotsky said...

I've been using this for a couple months:

function mkcd() {
mkdir -p "$@"
cd "$@"

smallawei said...




Avantime said...

Try to put this in your ~/.bash_profile: function mcd() { [ -n "$1" ] && mkdir -p "$1" && cd "$1"; }