Friday, January 17, 2025
HomeTechHow to mkdir only if a directory does not already exist?

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

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.
See also  4 panels in VS Code like RStudio

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.
See also  HTML align Attribute

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.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x