Create and change to a new directory in a single shell command

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";
        if [ ! -d $1 ]; then
            mkdir $1;
            cd $1;
            echo "$1 directory exists";

Save and close the file. Logout and login again or type the following command:
$ . ~/.bashrc

Now use mcd command:
$ mcd foo
$ pwd

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 4 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersncdu pydf
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
4 comments… add one
  • Hanifa Apr 24, 2007 @ 9:00

    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.

  • Duane Jul 10, 2007 @ 22:58


    If you use “mkdir -p $1;” then you can make nested directories.

    For example, mcd new_project/images


  • Sy Ali Jul 22, 2007 @ 12:22

    Just a quick thanks. I’ve been using a simplified version of this, but I like your version a lot. =)

  • slink Feb 21, 2008 @ 12:20

    Instead of using “==” you may choose “=” for testing equality, hence the method mentioned above would run on other shells, too.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum