32

Given a file path (e.g. /src/com/mot), how can I check whether mot exists, and create it if it doesn't using Linux or shell scripting??

1

6 Answers 6

31

With bash/sh/ksh, you can do:

if [ ! -d /directory/to/check ]; then
    mkdir -p /directory/toc/check
fi

For files, replace -d with -f, then you can do whatever operations you need on the non-existant file.

Sign up to request clarification or add additional context in comments.

7 Comments

You don't actually need the check. mkdir -p doesn't act on an existing directory.
That's a fair point. I'll leave it in though as if gives the OP the framework in case they wants to do other things before the mkdir.
Note that this gives a race condition in the case that the directory is created between the first and second line.
@Sjoerd Indeed, but that race condition (although with a much smaller window of probability) will also occur if you just use mkdir -p (unless some filesystem implements, and exposes, an atomic check-or-create function call). At least in the code above the mkdir call will not fail if invoked spuriously for an existing directory (because of the -p option provided anyway).
@Christian If you want an atomic check-or-create function, look no further than mkdir(2)
|
10

Check for directory exists

if [ -d "$DIRPATH" ]; then
    # Add code logic here 
fi

Check for directory does not exist

if [ ! -d "$DIRPATH" ]; then
    # Add code logic here
fi

Comments

9

mkdir -p creates the directory without giving an error if it already exists.

Comments

7

Well, if you only check for the directory to create it if it does not exist, you might as well just use:

mkdir -p /src/com/mot

mkdir -p will create the directory if it does not exist, otherwise does nothing.

Comments

6
test -d /src/com/mot || mkdir /src/com/mot

Comments

3

This is baisc, but I think it works. You'll have to set a few variables if you're looking to have a dynamic list to cycle through and check.

if [ -d /src/com/mot ];
then
    echo Directory found
else
    mkdir /src/com/mot
fi

Hope that's what you were looking for...

4 Comments

You're missing the ';' after the closing ']' of the if-clause.
@Chirstian The ';' is not needed after the ']', and the ']' is not a closing bracket. In the case of the command '[', the trailing ']' is just an argument to that command. The newline serves the same purpose as the semi-colon.
@WilliamPursell My comment was regarding the first revision of the question, which did not contain a newline after the ']' after the "test" command (or "brackets", sorry for missnaming it), in which case the ';' is required before the then, isn't it?
@christian, yes, either a newline or a ; is required. When I saw the question, the newline was in place.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.