Search code examples
bashshellrecursionsubdirectory

How can I create nonexistent subdirectories recursively using Bash?


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"

Solution

  • 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"