2 Ways to Make and Change into a Directory With One Line of Code

writing materials and a calculator

Nobody likes typing mkdir /path/to/foobar and then immediately typing cd /path/to/foobar. Let’s just do it all in one go. Here’s 2 ways to create a directory and change into it.

Method 1: Create the mkcd function

The first method is easy and requires no memorization. Write a quick function! Add this to your .zshrc / .bashrc / wherever you load your shell environment from.

mkcd() { mkdir -p "$@" && cd "$@" ; }

This line defines a function that takes the path / name of the desired directory, creates it with mkdir -p, then makes it the working directory with cd. Here’s how it should look like in action.

# using FULL PATH
$ mkcd /path/to/foobar
$ pwd
/path/to/foobar

# using a DIRNAME
$ mkcd babayaga
$ pwd
/path/to/foobar/babayaga

Note: the -p option will “Create intermediate directories as required.” (man 1 mkdir)

Method 2: Chain mkdir with cd && $_

Let’s say you need a quick and dirty method for a one-off task. Maybe it’s not worth defining a new function ¯\_(ツ)_/¯. Here we’ll make use of the $_ shell parameter.

$ mkdir /path/to/foobar && cd $_
$ pwd
/path/to/foobar

How does it work? If mkdir succeeds, everything after && is run. $_ returns the last argument to the previous command and passes it to cd. Please note the full behavior of $_ if you use it elsewhere:

The underscore variable is set at shell startup and contains the absolute file name of the shell or script being executed as passed in the argument list. Subsequently, it expands to the last argument to the previous command, after expansion. It is also set to the full pathname of each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file.

Bash Guide for Beginners (tldp.org)

Which Method Should I Use?

Use method #1, mkcd for machines you work on. Use method #2 in a pinch or in an environment where you don’t want to modify shell config files.

BONUS: I FORGOT THE mkcd FUNCTION!!! HELP!!!

Don’t worry. I’ve set up a github gist you can use from anywhere. I even made it easy to remember.

curl -L ascode.com/mkcd >> ~/.bashrc

That command will automatically fetch the contents of the gist (the mkcd function) and append it to your rc file! Switch .bashrc for whatever rc you need or simply use the curl part of the command for a quick reference!

2/17/2024 Update: Video Released!

Jedi Park Avatar

Posted by

Leave a Reply

Discover more from AsCode

Subscribe now to keep reading and get access to the full archive.

Continue reading