Q. How do I create a new directory and change to same in a single command? For example I need to create a directory called foo and change to same
mkdir foo
cd foo
How do I run both command at a time?
There is no such command exists that can create and change directory in a one pass. However you can create a shell function or alias to automate this task.
Howto creating and changing into a new Directory same time
Add following function to your bash startup file ~/.bash_profile or ~/.bashrc
$ vi ~/.bashrc
Append mcd() code:
mcd ()
{
if [ "$1" == "" ]; then
echo "mcd directory-name";
else
if [ ! -d $1 ]; then
mkdir $1;
cd $1;
else
echo "$1 directory exists";
fi;
fi
}Save and close the file. Logout and login again or type the following command:
$ . ~/.bashrc
Now use mcd command:
$ mcd foo
$ pwd
Featured Articles:
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- My 10 UNIX Command Line Mistakes
- Linux: 20 Iptables Examples For New SysAdmins

- 25 PHP Security Best Practices For Sys Admins
- The Novice Guide To Buying A Linux Laptop
- 10 Greatest Open Source Software Of 2009
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- Top 20 OpenSSH Server Best Security Practices
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Linux Video Editor Software
Facebook it - Tweet it - Print it -


{ 4 comments… read them below or add one }
HI,
I have found your tutorial useful but I’d like a clarify something. Is it required to place the semi-colon like as in C/C++ or not .
Cos I have seen u put ; for one fi and not for the other one.
I have tried without putting ; for any of the statement and it also works.
So is the semicolon neccesary.
thanks
Hi,
If you use “mkdir -p $1;” then you can make nested directories.
For example, mcd new_project/images
Cheers.
Just a quick thanks. I’ve been using a simplified version of this, but I like your version a lot. =)
Instead of using “==” you may choose “=” for testing equality, hence the method mentioned above would run on other shells, too.