views:

4944

answers:

6

I am writing a script to run under the korn shell on AIX. I'd like to use the mkdir command to create a directory. But the directory may already exist, in which case I don't want to do anything. So I want to either test to see that the directory doesn't exist, or suppress the "File exists" error that mkdir throws when it tries to create an existing directory.

Any thoughts on how best to do this?

+16  A: 

Try mkdir -p:

mkdir -p foo

Note that this will also create any intermediate directories that don't exist; for instance,

mkdir -p foo/bar/baz

will create directories foo, foo/bar, and foo/bar/baz if they don't exist.

If you want an error if parent directories don't exist, but want to create the directory if it doesn't exist, you can test for the existence of the directory first:

[ -d foo ] || mkdir foo
Brian Campbell
Thanks - I didn't realize -p would help me there.
Spike Williams
+1 for a nice all around explanation
alkar
+2  A: 

Use the -p flag.

man mkdir
mkdir -p foo
jimmyorr
+5  A: 

This should work:

$ mkdir -p dir

or:

if [[ ! -e $dir ]]; then
    mkdir $dir
elif [[ ! -d $dir ]]; then
    echo "$dir already exists but is not a directory" 1>&2
fi

which will create the directory if it doesn't exist, but warn you if the name of the directory you're trying to create is already in use by something other than a directory.

Alnitak
I don't think there's a -d operator in korn, rather -e is used for both files / directories and just checks existence. Also, they all return 0 upon success, so ! is redundant. Correct me if I'm wrong.
alkar
wrong on both counts, AFAIK. tests return _true_ on success, and -d exists too (at least on MacOS X)
Alnitak
indeed you are right on both accounts and I'm wrong :Pbeen a long time since I used ksh, thanks for making me look it up hehe +1
alkar
Should that "end" statement be an "fi"?
Spike Williams
@spike - yes, fixed...
Alnitak
+2  A: 

Or if you want to check for existence first:

if [[ ! -e /path/to/newdir ]]; then
            mkdir /path/to/newdir
fi

-e is the exist test for korn shell.

You can also try googling a korn shell manual.

alkar
AFAIK this test needs negating.
Alnitak
+1  A: 

Just mkdir again... if it already exsits... so what?

phillc
Functionally, it doesn't matter, but I didn't want the clutter of an error message in my output.
Spike Williams
Ahh, ok. that makes sense.
phillc
So you redirect stderr, as in Pax's answer.
skiphoppy
You are correct that if the directory exists, a second mkdir is harmless; but if there is a file that exists with the name you want to use for your directory, redirecting stderr will prevent you from finding out.
Thomas L Holaday
+2  A: 

The old tried and true

mkdir /tmp/qq >/dev/null 2>&1

will do what you want with none of the race conditions many of the other solutions have.

Sometimes the simplest (and ugliest) solutions are the best :-)

paxdiablo