How can I create nonexistent subdirectories recursively using Bash?

BashShellRecursionSubdirectory

Bash Problem Overview


I am creating a quick backup script that will dump some databases into a nice/neat directory structure and I realized that I need to test to make sure that the directories exist before I create them. The code I have works, but is there a better way to do it?

[ -d "$BACKUP_DIR" ] || mkdir "$BACKUP_DIR"
[ -d "$BACKUP_DIR/$client" ] || mkdir "$BACKUP_DIR/$client"
[ -d "$BACKUP_DIR/$client/$year" ] || mkdir "$BACKUP_DIR/$client/$year"
[ -d "$BACKUP_DIR/$client/$year/$month" ] || mkdir "$BACKUP_DIR/$client/$year/$month"
[ -d "$BACKUP_DIR/$client/$year/$month/$day" ] || mkdir "$BACKUP_DIR/$client/$year/$month/$day"

Bash Solutions


Solution 1 - Bash

You can use the -p parameter, which is documented as:

> -p, --parents > > no error if existing, make parent directories as needed

So:

mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"

Solution 2 - Bash

mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"

Solution 3 - Bash

While existing answers definitely solve the purpose, if you’re looking to replicate a nested directory structure under two different subdirectories, then you can do this:

mkdir -p {main,test}/{resources,scala/com/company}

It will create the following directory structure under the directory from where it is invoked:

├── main
│   ├── resources
│   └── scala
│       └── com
│           └── company
└── test
    ├── resources
    └── scala
        └── com
            └── company

The example was taken from this link for creating an SBT directory structure.

Solution 4 - Bash

mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1	subdir2	subdir3	subdir4	subdir5	subdir6	subdir7	subdir8

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTopher FangioView Question on Stackoverflow
Solution 1 - BashbmarguliesView Answer on Stackoverflow
Solution 2 - BashJonathan FeinbergView Answer on Stackoverflow
Solution 3 - Bashy2k-shubhamView Answer on Stackoverflow
Solution 4 - Bashnitrohuffer2001View Answer on Stackoverflow