How to mkdir only if a dir does not already exist?

2019-01-05 06:48发布

I am writing a shell script to run under the KornShell (ksh) on AIX. I would like to use the mkdir command to create a directory. But the directory may already exist, in which case I do not want to do anything. So I want to either test to see that the directory does not 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?

13条回答
姐就是有狂的资本
2楼-- · 2019-01-05 07:15

Defining complex directory trees with one command

mkdir -p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}
查看更多
趁早两清
3楼-- · 2019-01-05 07:18

mkdir foo works even if the directory exists. To make it work only if the directory named "foo" does not exist, try using the -p flag.

Example :-

mkdir -p foo

This will create the directory named "foo" only if it does not exist. :)

查看更多
欢心
4楼-- · 2019-01-05 07:24

If you don't want to show any error message:

[ -d newdir ] || mkdir newdir

If you want to show your own error message:

[ -d newdir ] && echo "Directory Exists" || mkdir newdir
查看更多
时光不老,我们不散
5楼-- · 2019-01-05 07:24

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.

查看更多
倾城 Initia
6楼-- · 2019-01-05 07:24

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.

查看更多
放荡不羁爱自由
7楼-- · 2019-01-05 07:25

This is a simple function (bash shell) which lets you create a directory if it doesn't exist.

#----------------------------------
# Create a directory if it doesn't exist
#------------------------------------
createDirectory() {
    if [ ! -d $1 ]
        then
        mkdir -p $1
    fi
}

You can call the above function as :

createDirectory /tmp/fooDir/BarDir

The above creates fooDir and BarDir if they don't exist. Note the "-p" option in mkdir command which creates directories recursively. Hope this helps.

查看更多
登录 后发表回答