Function
You can make a small function, which you can store in the file ~/.bashrc
. Edit the file to add the following lines,
md () {
mkdir "$1" && cd "$1"
}
Run
source ~/.bashrc
in order to make the change work in the current terminal [window]. The new function will be there, when you open new terminals.
Using &&
between the commands makes the cd
command run only if the mkdir
command was successful.
Example: I can use the function md
like this to create a test directory testdir
in the current directory (in this case my home directory as seen from the prompt),
sudodus@xenial32 ~ $ md testdir
sudodus@xenial32 ~/testdir $
Bash shellscript did not work as I expected
I will also describe my difficulties using a small bash shellscript for this purpose, because other people might try it and get confused.
You can store a shellscript in the directory ~/bin
. After creating ~/bin
and rebooting, it will be in PATH.
Use a name that is not used by any standard command (for example mdscript
),
#!/bin/bash
mkdir "$1" && cd "$1"
Make the script executable
chmod ugo+x ~/bin/mdscript
This does not work as intended with
mdscript testdir
because the current directory is only changed in the sub-process of the shell-script, but not in the terminal [window] after finishing the shellscript.
It works when 'sourced', run with the command line
source mdscript testdir
but this is not convenient, not a good answer to the original question.
You can see how it works, if you add a pwd
command into the shellscript
#!/bin/bash
mkdir "$1" && cd "$1"
pwd
and run the script mdscript
sudodus@xenial32 ~ $ mdscript testdir
/home/sudodus/testdir
sudodus@xenial32 ~ $
$ mkdir /path/to/dir && cd /path/to/dir