[Linux] How to make a directory and automatically switch to it
by Riley MacDonald, December 28, 2017

Generally when I create a new directory using mkdir I want to switch to it immediately. For some reason there’s no argument to achieve this. As explained in a previous post I manage my dotfiles using Git. Here’s the function which adds a -c argument to mkdir which will automatically cd into that directory. Add the following to your relevant ~/.bashrc, ~/.bash_profile profile.

1
2
3
4
5
6
mkdir () {
  case $1 in
    (-c) command mkdir -p "$2" && cd "$2";;
    (*)  command mkdir "$@";;
  esac
}

Example Usage
Here’s how to use the new function:

# Create a directory and immediate switch to it
~/Documents $ mkdir -c temp
~/Documents/temp $
 
# Create a directory like normal
~/Documents $ mkdir temp
~/Documents $
Open the comment form

Leave a comment:

Comments will be reviewed before they are posted.

User Comments:

How to write a custom Gradle plugin in groovy - Riley MacDonald on 2017-12-28 20:32:28 said:
[…] Initialize a new git repository Switch to new directory to hold the plugin (see my post on using the -c argument with mkdir): […]