About Linux FAQ

Browse More FAQs:

Advertisements

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

Posted by Vivek Gite [Last updated: March 16, 2007]

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

Subscribe to our free e-mail newsletter or RSS feed to get all updates. You can Email this page to a friend.

Related Other Helpful FAQs:

Discussion on This FAQ

  1. Hanifa Says:

    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

  2. Duane Says:

    Hi,

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

    For example, mcd new_project/images

    Cheers.

  3. Sy Ali Says:

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

  4. slink Says:

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

Leave a Reply

We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Copyright © 2006-2008 nixCraft. All rights reserved - TOS/Disclaimer - Privacy policy - Sitemap - Powered by Open source software.