So ... if you do a lot of command line work, you know that it is a drag to mkdir (create) a new folder and then have to separately cd into it. Especially if you do this a lot.
Here's a 3 letter command to do both.
First, let's get this up and working; and then we'll go over some of the parts for anyone that is new to this.
Enter the below mcd (make a folder and then cd into it) function into your .bashrc file.
mcd ()
{
if [[ $# -eq 0 ]] ; then
echo "Enter the (path)directory to create!"
echo "usage: "
echo " mcd files"
echo " mcd work/files"
echo " ...or for folders with spaces, add quotes:"
echo " mcd 'work/new files'"
echo " mcd "work/new files""
# exit 0
fi;
# -n checks if the folder is already there.
# If not, the directory (with parents) is created.
# Either way it then cds into the desired folder.
[ -n "$1" ] && mkdir -p "$*" && cd "$1";
echo "current directory: " $(pwd)
}
Then $ source .bashrc
to implement it (or just open another terminal).
Now you can type $ mcd your-desired-foldername
and it will create the folder your-desired-foldername, after first checking if it needs to do so. That's what this part [ -n "$1" ] &&
does.
It continues on to cd into the folder. Finally it will show you the path that you are in; just to confirm that it all worked. That's this part echo "current directory: " $(pwd)
.
By adding the -p parameter to mkdir, mcd handles creating all folders in the path provided; building any required parent folders along the way.
The if [[ $# -eq 0 ]] ;
portion of code near the top of mcd is checking to make sure a folder name was given as a mcd parameter. It will print out usage instructions if nothing was provided.
If no parameter is passed in, this will be the result:
One usage note.
Like mkdir, mcd wants to have quotes ( ' or " ) around folder names containing spaces. Otherwise they'll try to create separate folders for each portion of the space-separated name.
So use:
$ mcd "my work files"
rather than
$ mcd my work files
if your folder names contain spaces.