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

@ İsmail Baydan

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.

  1. Create a single directory: You can create single directory with sub directories like below.

    mkdir -p /path/to/directory
    
  2. 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 named nested .

    mkdir -p /path/to/nested/directory
    
  3. 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 named example1 , example2, example3

    for i in {1..10}; do mkdir -p "example$i"; done
    
  4. 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"
    
  5. Create directories with special characters in their names: You can create directories with special characters in their names.

    mkdir -p "/path/with-special_chars/!@#$%^&*()"
    
  6. 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
    
  7. 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)"
    
  8. 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"
    
  9. 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}
    
  10. 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.

© 2024 Linux and Python Tutorials

🌱 Powered by Hugo with theme Dream.