img

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

September 8, 2019

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

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Article Tags:
Article Categories:
How To

Comments are closed.