shell - How to mkdir only if a directory does not already exist?

ID : 305

viewed : 165

Tags : shellscriptingkshaixmkdirshell





Top 5 Answer for shell - How to mkdir only if a directory does not already exist?

vote vote

94

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.

Some implementation like GNU mkdir include mkdir --parents as a more readable alias, but this is not specified in POSIX/Single Unix Specification and not available on many common platforms like macOS, various BSDs, and various commercial Unixes, so it should be avoided.

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 
vote vote

88

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.

vote vote

76

Use the -p flag.

man mkdir mkdir -p foo 
vote vote

70

Defining complex directory trees with one command

mkdir -p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a} 
vote vote

55

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 

Top 3 video Explaining shell - How to mkdir only if a directory does not already exist?







Related QUESTION?