Combined `mkdir` and `cd`?

I think creating a function is the most appropriate way to do this, but just for listing all alternative ways, you could write:

mkdir foo && cd "$_"

$_is a special parameter that holds the last argument of the previous command. The quote around $_ make sure it works even if the folder name contains spaces.

Why use double quotes?

In some shells, such as zsh, the double quotes surrounding the $_ are not necessary even when the directory name contains spaces. They are required for this command to work in bash, however.

For example, running this command in bash 3.2.57 on macOS 10.13.6:

mkdir "my directory" && cd $_

results in this output:

bash: cd: my: No such file or directory

However, if we surround $_ with double quotes, the command returns successfully.

bash-3.2$ mkdir "my directory" && cd "$_"
bash-3.2$ echo $?
0
bash-3.2$

Function?

mkcdir ()
{
    mkdir -p -- "$1" &&
      cd -P -- "$1"
}

Put the above code in the ~/.bashrc or another file sourced by the ~/.bashrc. Then restart the terminal for changes to apply.

After that simply run mkcdir foo or mkcdir "nested/path/in quotes".

Notes:

  • "$1" is the first argument of the mkcdir command. Quotes around it protects the argument if it has spaces or other special characters.
  • -- makes sure the passed name for the new directory is not interpreted as an option to mkdir or cd, giving the opportunity to create a directory that starts with - or --.
  • -p used on mkdir makes it create extra directories if they do not exist yet, and -P used makes cd resolve symbolic links.

Bash (using word designators):

/tmp/bug$ mkdir "some dir"
/tmp/bug$ cd !$
cd "some dir"
/tmp/bug/some dir$ 

!$ expands to the last argument of the previous line in the history. If you have parameters in between, then you can use !:1 for the first argument, !:2 forthe second argument, etc.

From bash(1):

Event Designators

An event designator is a reference to a command line entry in the history list. Unless the reference is absolute, events are relative to the current position in the history list.

! Start a history substitution, except when followed by a blank, newline, carriage return, = or ( (when the extglob shell option is enabled using the shopt builtin).

[..]

Word Designators

Word designators are used to select desired words from the event. A : separates the event specification from the word designator. [..]

[..]
n The n-th word.
^ The first argument. That is, word 1.
$ The last word. This is usually the last argument, but will expand to the zeroth word if there is only one word in the line.