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 06:59
mkdir -p sam
  • mkdir = Make Directory
  • -p = --parents
  • (no error if existing, make parent directories as needed)
查看更多
放荡不羁爱自由
3楼-- · 2019-01-05 07:00

Use the -p flag.

man mkdir
mkdir -p foo
查看更多
放荡不羁爱自由
4楼-- · 2019-01-05 07:03

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 when parent directories don't exist, and want to create the directory if it doesn't exist, then you can test for the existence of the directory first:

[ -d foo ] || mkdir foo
查看更多
Fickle 薄情
5楼-- · 2019-01-05 07:03

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.

查看更多
【Aperson】
6楼-- · 2019-01-05 07:04

mkdir does not support -p switch anymore on Windows 8+ systems.

You can use this:

IF NOT EXIST dir_name MKDIR dir_name
查看更多
萌系小妹纸
7楼-- · 2019-01-05 07:07
directory_name = "foo"

if [ -d $directory_name ]
then
    echo "Directory already exists"
else
    mkdir $directory_name
fi
查看更多
登录 后发表回答