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
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 $?