If you spend any time in the Terminal at all, you probably use the mkdir command to create a directory, and then the cd command to change to that directory right after. However, there is a way to do both of those actions with one command.

You can run two commands at once on the command line manually, but we’ll show you how to add a line to the .bashrc file that will combine the mkdir command and the cd command into one custom command you can type with a directory name.

RELATED: How to Run Two or More Terminal Commands at Once in Linux

The .bashrc file is a script that runs every time you open a Terminal window by pressing Ctrl+Alt+T or open a new tab in a Terminal window. You can add commands to the .bashrc file that you want to run automatically every time you open a Terminal window.

To edit the .bashrc file, we’re going to use gedit. Type the following command at the prompt.

gedit ~/.bashrc

You can use any text editor you’re comfortable with, like vi or nano. Simply replace “gedit” in the above command with the command to run your chosen text editor.

Scroll to the bottom of the .bashrc file and add the following line to the end of the file. We recommend you copy the line below and paste it into the .bashrc file.

mkdircd(){ mkdir "$1" && cd "$1" ; }

This is essentially a function that will run the two commands one right after the other. The new custom command in our example is called mkdircd (you can actually name the command whatever you want) and it will run the mkdir command and then the cd command. The "$1" on both commands indicates that the commands will accept one value to operate on. In this case, it’s the name of the new directory.

You can add a comment above the command so you remember what the command does. Simply put a pound sign (#) at the beginning of the line, and then any description you want to add.

Click “Save”.

Close gedit (or other text editor) by clicking the “X” in the upper-left corner of the window.

The setting you just added to the .bashrc file will not affect the current Terminal window session. You must close the Terminal window and log out and back in for the change to take affect. So, type exit at the prompt and press Enter or click the “X” button in the upper-left corner of the window. Then, log out and back in.

Now, when you type the new command followed by a new directory name, the mkdircd function you created in the .bashrc file is called and the directory name “Test\ Directory” is passed to the two commands ( mkdir and cd ). The “Test Directory” directory will be created and you will be immediately taken to it.

If you manage your directories using the command line, this trick can save you some time.

Profile Photo for Lori Kaufman Lori Kaufman
Lori Kaufman is a technology expert with 25 years of experience. She's been a senior technical writer, worked as a programmer, and has even run her own multi-location business.
Read Full Bio »