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

Following Jesus; Husband; Father; Developer; Gamer; Tinkerer; Writing about code
Search for a command to run...

Following Jesus; Husband; Father; Developer; Gamer; Tinkerer; Writing about code
No comments yet. Be the first to comment.
Today ChatGPT lied to me, so I’m setting the record straight. This is my question: “If an endpoint in an OpenAPI spec has multiple tags, what will Swagger Codegen do?”. Because Swagger Codegen organized the generated code into api/tag_name_api files....

A Short Story

Universal Libraries, The Internet, and Generative AI

This is the article I wished existed when I needed to support accounting functions. Double-entry Bookkeeping may seem esoteric and unnecessarily complicated, but actually describes a simple framework for maintaining a correctible and auditable record...

How to Change Databases without Downtime

Almost every new project seems to start with the same thing:
$ mkdir new-project
$ cd new-project
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 "$@" }
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 "$@" }
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 "$_" }
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:
mcd() { mkdir "$@" 2> >(sed s/mkdir/mcd/ 1>&2) && cd "$_"; }
For more examples of how this is used, check out my gist.