DEV Community

loading...
Cover image for One Liner to Create and Move into a Directory (combining mkdir + cd)

One Liner to Create and Move into a Directory (combining mkdir + cd)

Nathan Kallman
Husband; Father; Software Engineer; Gamer; Tinkerer; Writing about code on DEV.
・1 min read

Almost every new project seems to start with the same thing:

$ mkdir new-project
$ cd new-project
Enter fullscreen mode Exit fullscreen mode

In a GUI we would be stuck; but in the command line, we can make this one command instead of two!

Let's make a little function called mcd (for make and change directory). First we need to make the directory:

mcd() { mkdir "$@" }
Enter fullscreen mode Exit fullscreen mode

The "$@" refers to all the arguments given to mcd when it is used. At this point, we've basically made a round about alias for mkdir. So how about adding the cd part now?

mcd() { mkdir "$@" && cd "$@" }
Enter fullscreen mode Exit fullscreen mode

And this kind of works. The problem is mkdir can receive a whole bunch of flags and even multiple directories to create at once, but cd really only expects one argument, the directory to move into. The good thing about how these commands are structured is mkdir expects the last argument to be a directory, which makes it easy for us to pick out the one directory that was created (or if many were created, pick out the last one created) using "$_", which refers to the last argument of the previously executed command.

mcd() { mkdir "$@" && cd "$_" }
Enter fullscreen mode Exit fullscreen mode

And we could be done here, but I added one more thing. If mkdir prints errors, they will all be written in terms of mkdir. But that makes little sense to someone who just ran a command called mcd. I fixed that with sed and some redirection:

For more examples of how this is used, check out my gist.

Discussion (0)