To create a directory in Unix/Linux using the mkdir
command only if it does not already exist, you can use the -p
flag. The -p
option prevents the command from throwing an error if the directory already exists, and it will only create the directory if it doesn’t exist.
Command:
mkdir -p /path/to/directory
Explanation:
- The
-p
option stands for “parents,” which allows the command to create any missing parent directories as well, but its key feature here is that it doesn’t generate an error if the directory already exists.
If the directory already exists, it simply does nothing. If it does not exist, it creates the directory and any missing parent directories.
Example:
mkdir -p /home/user/new_directory
- If
/home/user/new_directory
already exists, nothing happens, and no error is thrown. - If
/home/user/new_directory
does not exist, it will be created.
Verifying:
You can check if the directory exists or was created using the ls
command:
ls -ld /home/user/new_directory
If the directory exists, this will list the directory’s details. If it does not exist, you will get an error like ls: cannot access '/home/user/new_directory': No such file or directory
.