Create a Directory and `cd` into it in one command

Reading Time: 2 minutes

(This post is meant not only to describe a little shell function, but to introduce you to a powerful, yet simple concept.)

When I’m working with a command line, I will frequently need to create a directory and then immediately change to that directory.

Let’s say I’m starting a new project.  I will cd  into my ~/projects directory and then create a new folder where I’ll be putting my files.  After creating the new folder, I’ll generally need to `cd` to that folder.

cd ~/projects
mkdir foo
cd foo

My first thought was to write a little `alias` that combined the two operations, but aliases don’t really handle parameters well, so I wrote it as a shell function.  (I use the amazing `zsh` as my terminal shell, but this approach works just the same in bash.)
In the below example, the “$1” refers to the argument passed. “$2”, “$3” and so on also work. (Be sure to quote them!)

mgo () {
mkdir "$1"
cd "$1"
}

You can paste that into your shell and it will work for the duration of your session, but of course the better way of making it available is to put it in your `~/.zshrc` or whatever your ~/.profile file is in your shell of choice. For example, in OS X, you have to first create the file:

Start up Terminal.
Type "cd ~/" to go to your home folder.
Type "touch .bash_profile" to create your new file.
Edit .bash_profile with your favorite editor (or you can just type "open -e .bash_profile" to open it in TextEdit.

To use it, you need to have that file be re-read, so you can either close and re-open your terminal, `source` the file you just edited, or just paste the function in to have it be active for the current session.

I realize that this is an insanely simple thing to worry over, but so much of the Linux/Unix philosophy is about making things just a bit more efficient and shell functions are a very approachable way to craft your own customizations for efficiency.

Another Example:
If you’re a python programmer or student, you are probably aware of venv, the virtual environment for Python that create lightweight Virtual Environment on a directory-by-directory basis. If you have, you know that each time you move to a project directory, you need to type `./venv/bin/activate` to set up the environment. A clever function I found a while back takes over the `cd` command to check for a virtual environment and activate it if it exists:
cd () {
builtin cd $1
if [[ -d ./venv/bin ]]
then
source ./venv/bin/activate
fi
if [[ -d ./bin ]]
then
source ./bin/activate
fi
}

Both of the above examples are simple, but useful. Please leave a comment below if you know of any other good examples, or can think of a good use case for a function.

Leave a Reply