Make an alias to create and change into a new folder on the command line
Wed, Jul 26, 2023
2-minute read
Sick of typing $ cd someFolder
and $ mkdir someFolder
? If you live in the terminal enough, it gets annoying. Here’s a shortcut.
Add the following alias to your bash profile (usually found at ~/.bashrc
or ~/.bash_profile
):
alias cdd='function _cdd() { mkdir -p "$1" && cd "$1"; unset -f _cdd; }; _cdd'
This is how it works:
alias cdd=...
sets up the aliascdd
to the following command.function _cdd() {...}; _cdd
is a temporary function that is immediately called. This structure is necessary because aliases can’t accept arguments directly. The function definition and call are both included in the alias command.mkdir -p "$1"
creates a new directory with the name given by the first argument. The-p
flag tellsmkdir
to create parent directories as needed.&&
only runs the following command if the previous command succeeded, ensuring that we don’tcd
into a directory that wasn’t created successfully.cd "$1"
changes the current working directory to the new directory.unset -f _cdd
removes the function definition after it’s used to avoid conflicts with any other functions or commands.
Remember to source your bash profile after adding the alias for the changes to take effect. You can do this with the command source ~/.bashrc
or source ~/.bash_profile
, depending on which file you added the alias to.