Mkdir file exists linux

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

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. How can I best do this?

17 Answers 17

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

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:

the shortened example you use is exactly what you should not do. It is reversing the logic to save coding space but it should use ! and && and make more sense to those reading it.

@AndreasLarsen This question is about mkdir on Unix-like systems, not on Windows. -p is required for POSIX/Single Unix Specification compliance, so anything that intents to comply with those specifications will support -p . Windows is entirely different, unless you use a POSIX emulation layer like Cygwin or MSYS.

I discovered something interesting today with mkdir -p , you can use brackets! <> to create «complex» directory tree in a command. See here: technosophos.com/2010/04/15/…

@MikeQ I ‘d prefer || instead of && because then the whole line has the right exit status. Important if your shell runs with errexit or if that line is the last one in a function, switch-case, whatever.

@herve That has nothing to do with mkdir ; the shell expands such an expression to a discrete list of argument that are passed to mkdir .

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.

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.

it might be worth mentioning that this isn’t quite thread-safe. between the time that you check if the directory exists and the time you try to write, things might change.

Defining complex directory trees with one command

Читайте также:  Linux просмотр все соединений

Keep in mind that this is not a feature of mkdir itself, but the shell that executes the command. It’s called brace expansion — AFAIK, only Bash, ksh, zsh, and the C shell support it.

@Atlas7 stated, you will need to escape characters that are normally part of regex. (i.e. instead of using folder name you need to use folder\ name )

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

If you want to show your own error message:

[ -d newdir ] && echo "Directory Exists" || mkdir newdir 

@PeterMortensen : Of course. Use mkdir -p if you do not want race conditions. But you won’t get to show your own Directory exists error.

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.

This will create the directory named «foo» only if it does not exist. 🙂

As mentioned by @BrianCampbell, this will also create any other directories in the path. This can be dangerous if e.g. a volume becomes unmounted, as it may create directories in the mount point.

mkdir -p /my/new/dir >/dev/null 2>&1 

Does mkdir -p /parent/dir complain if permissions prevent creating /parent/dir ? If so, perhaps the redirection might be considered «deadly» or at least unwise.

You can either use an if statement to check if the directory exists or not. If it does not exits, then create the directory.

if [ ! -d $dir ] then mkdir $dir else echo "Directory exists" fi 

mkdir -p also allows to create the tree structure of the directory. If you want to create the parent and child directories using same command, can opt mkdir -p

mkdir -p /home/parent_dir /home/parent_dir/child1 /home/parent_dir/child2 

I have shared you ways of creating the folders when an folder does not exists. It depends upon the requirement on the one. If you have a use case where you need to check if folder does not exist and you want to keep track of that so you can go with solution 1. If it does not matter, you can go with solution 2, it will create the folder if not exists.

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.

@Peter, a snippet like (for example) [ -d newdir ] || mkdir newdir , where the directory does not initially exist, has a race condition in that, between the test for existence and the attempted creation, another process could swoop in and create the directory. Hence the mkdir would then fail.

@Mike Q: the base path /tmp has likely been chosen in the example to represent a base-path that always exists and is write-able to the current user, e.g. the user has enough rights to create a directory in. You raise a valid point thought:: the logic is a bit contradictory, as when this command fails, it can mean two things: 1.) the directory exists or 2.) the directory could not be created. This is not true for the operation itself, therefore a simple post-check on the directory path can give the confirmation, or the next command that operates on.

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

IF NOT EXIST dir_name MKDIR dir_name 
directory_name = "foo" if [ -d $directory_name ] then echo "Directory already exists" else mkdir $directory_name fi 

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

#------------------------------------------# # Create a directory if it does not exist. # #------------------------------------------# # Note the "-p" option in the mkdir # # command which creates directories # # recursively. # #------------------------------------------# createDirectory()

You can call the above function as:

createDirectory «$(mktemp -d dir-example.XXXXX)/fooDir/BarDir»

The above creates fooDir and BarDir if they don’t exist. Note the «-p» option in the mkdir command which creates directories recursively.

Читайте также:  Межсетевой экран linux mint

Referring to man page man mkdir for option — p

 -p, --parents no error if existing, make parent directories as needed 

which will create all directories in a given path, if exists throws no error otherwise it creates all directories from left to right in the given path. Try the below command. the directories newdir and anotherdir doesn’t exists before issuing this command

Correct Usage

mkdir -p /tmp/newdir/anotherdir

After executing the command you can see newdir and anotherdir created under /tmp. You can issue this command as many times you want, the command always have exit(0) . Due to this reason most people use this command in shell scripts before using those actual paths.

Источник

Make Directory Only if it Doesn’t Exist Already in Linux

It’s better to be careful and prevent errors while creating directories in case there are files or directories with the same name in the same location.

To create a directory in Linux, you use the mkdir command. It stands for ‘make directory’ after all. It’s quite a simple command.

But, when you try to create a directory that already exists, you get an error like:

$ mkdir dir0 mkdir: cannot create directory ‘dir0’: File exists

This indicates that if a directory already exists, the mkdir command will not try to create or modify the already existing directory in any way.

But it also shows an error which is not what you always want especially if you are writing a bash script.

To prevent this error, use the -p flag along with mkdir command.

This way, though the directory is not created, it won’t show any error as well. Your scripts will run as usual.

You’ll get the same error if a file or link exists with the same name as the directory you are trying to create. Why? Because everything is a file in Linux. A directory is a special file that acts like an index of all the files that are inside it.

Let’s see things in a bit more detail here and discuss various ways of preventing this error.

Method 1: Use ‘-p’ option

If you look at the manpage of the mkdir command, it has the ‘-p’ flag.

The use of ‘-p’ flag in mkdir is «no error if existing, make parent directories as needed».

When you use the ‘-p’ flag, the mkdir utility will check if a directory, file, link or pipe with the same name does not exist already.

If the does exist, it will not modify your existing directory or file, nor will it show an error message.

This is very handy when you are creating custom bash scripts and don’t want its execution to stop because of this error.

The -p can also be used to create a nested directory structure. If you want to create dir1/dir2/dir3 like directory structure and some or none of the directories exist in the hierarchy.

Читайте также:  Авто переключение языка ввода linux

Method 2: Check if directory already exists in bash

If you are writing bash scripts, you can use the if condition and check if the directory already exists. If it doesn’t then you create the directory.

if [ -d my_dir ] then mkdir my_dir fi

Method 3: Send it to the void

A majority of UNIX tools have two output streams, stdout and stderr. Normally, both streams, stdout and stderr get printed to the terminal. But you can redirect either the normal output stream or the error stream to another file.

So, when the mkdir command throws an error to your terminal, you can redirect it to the void.

To redirect stdout, use it along with the ‘1’ numerical stream descriptor, for stderr, use the numerical stream descriptor ‘2’. You can also redirect stdin by using the ‘0’ stream descriptor.

To actually redirect the output, use the appropriate stream descriptor along with the redirection operator ‘>’

This will send the output of stderr to the ‘/dev/null’ device which discards anything that gets written to it.

This is totally safe to do. As I mentioned earlier, if the directory already exists, then it will not be modified. Only an error message will be shown. All you are doing here is suppressing that error message.

Personally, I would go with the first method i.e. using the mkdir -p command for ensuring that the directory is created only if there is no file or directory of the same name in the same location.

Источник

How To “mkdir” Only If Directory Not Exist In Linux?

How To

Linux mkdir command is used to create directories. The mkdir command creates directories that don’t exist. But in some cases, the directory may already exist where we do not want to create or recreate the directory. You may ask how can I accomplish this if the directory exists does not run mkdir command?

Directory Existince Check with -p Option

The mkdir command provides the -p option which is used to parent check. The -p option also used to create multi level directories by checking parents. We can use the -p in order to check the specified directory existence. If the specifed directory exists the command sliently skips create of the directory. First look how the mkdir command behaves by defualt if the specified directory exist.

mkdir: cannot create directory ‘data/backup1’: File exists

We can see from the output that if the specified directory exist it returns error like “cannot create directory” etc. It also prints the message “File exists”.

The -p option can be used to check the directory existence and do not create new direrctory if exist and create directory if not exist.

Directory Existince Check with Bash Script

Bash can be used to check the directory existence and prevent “File exists” error. Generally bash scripts are used to check directory existence and create directory if the directory not exist. The following script checks the directory existence with the conditional.

[ -d /var/data/backup ] || mkdir var/data/backup

Supress “File Exist” Error

Also the mkdir command can be used wihtout any option. The error message can be suppressed and redirected into the /dev/null device. This do not prints the error code and error message to the standard output.

mkdir /var/data/backup >/dev/null 2>&1

Источник

Оцените статью
Adblock
detector