The mkdir
command is used to create directories in Unix-like operating systems. However, when using mkdir
, it’s common to encounter situations where the directory you want to create already exists. In such cases, mkdir
will throw a "File exists" error. This tutorial will explore ways to create directories conditionally, avoiding this error.
Using the -p
Flag
The most straightforward way to create a directory only if it doesn’t exist is by using the -p
flag with mkdir
. The -p
flag stands for "parents," and it not only creates the specified directory but also any parent directories that don’t exist. This approach ensures that you won’t encounter an error due to a missing parent directory.
mkdir -p foo
This command will create the foo
directory if it doesn’t already exist, along with any necessary parent directories. For example:
mkdir -p foo/bar/baz
will create foo
, foo/bar
, and foo/bar/baz
if they don’t exist.
Testing for Directory Existence
If you want to avoid creating intermediate directories and simply check if the target directory exists before attempting to create it, you can use a conditional statement with the [ -d dir ]
test. This checks if dir
is an existing directory.
[ -d foo ] || mkdir foo
This command says: "If foo
is not an existing directory ([ -d foo ]
returns false), then create it (mkdir foo
)".
Handling Existing Non-Directory Files
In some cases, you might want to ensure that the name you’re trying to use for a directory isn’t already in use by another type of file (like a regular file or a symbolic link). You can achieve this with an if
statement that checks both if the item exists and if it’s not a directory:
if [[ ! -e $dir ]]; then
mkdir $dir
elif [[ ! -d $dir ]]; then
echo "$dir already exists but is not a directory" 1>&2
fi
This script checks if $dir
does not exist (! -e $dir
). If it doesn’t, the script creates the directory. However, if $dir
exists but isn’t a directory (! -d $dir
), it outputs an error message indicating that $dir
is already in use by another type of file.
Creating Complex Directory Trees
The -p
flag also allows for the easy creation of complex directory structures using path expansion. For example:
mkdir -p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}
This command creates a detailed structure under the project
directory, including all specified subdirectories and their parents if they don’t exist.
Conclusion
Creating directories conditionally with mkdir
can be efficiently managed using the -p
flag or by testing for directory existence. These approaches help avoid errors due to existing files or missing parent directories, making your scripts more robust and flexible.