How to mkdir -p only if a directory does not already exist?
Wednesday, Aug 7, 2024 | 2 minutes read | Update at Wednesday, Aug 7, 2024
Linux bash provides the mkdir
command in order to create directory. By default the mkdir command creates single directory but can not create child or sub directories. The mkdir -p
command is used to create new directory with subdirectories or child directories.
-
Create a single directory: You can create single directory with sub directories like below.
mkdir -p /path/to/directory
-
Create multiple nested directories: You can create single directrory with nested child directories. In the following example we create the directory
path
with nested directory namednested
.mkdir -p /path/to/nested/directory
-
Create multiple directories in a loop: We can use
mkdir -p
in order to create multiple directories by using bash for loop. In the following example we will create directories namedexample1
,example2
,example3
…for i in {1..10}; do mkdir -p "example$i"; done
-
Create directories with spaces in their names: We can create new directories with sub directories where the directory names contain spaces.
mkdir -p "/path/with spaces/in the name"
-
Create directories with special characters in their names: You can create directories with special characters in their names.
mkdir -p "/path/with-special_chars/!@#$%^&*()"
-
Create multiple directories at once (comma-separated): We can use the
mkdir -p
command in order to create multiple directories at once just running single command.mkdir -p /dir1 /dir2 /dir3
-
Create directories with a date in their names: We can use the
mkdir -p
command to create new directories where their names contain dates like current date.mkdir -p "/backup/$(date +%Y-%m-%d)"
-
Create directories with a variable in their names: We can use the
mkdir -p
command to create directories by using bash variables to set their names.directory_name="my_directory" mkdir -p "/path/to/$directory_name"
-
Create a directory structure for a project: We can use
mkdir -p
in order to create directory structure. We can put the child directory names inside the{ }
and separate their names with command.mkdir -p /project/{src,bin,docs}
-
Create directories with permissions (using
install
command as an alternative):install -d -m 755 /path/to/directory
These examples illustrate the versatility of mkdir -p
in creating directories with various configurations and conditions.