228

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

4 Answers 4

507

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"
6
  • 37
    @bmargulies - Holy crap that was way simpler than I thought =P Nov 13, 2009 at 20:48
  • Upvoted because you're a deletionist. Oops, already did about a year ago! Feb 3, 2015 at 21:50
  • 1
    It doesn't work if user has no right to read one of intermittent folders Apr 22, 2018 at 8:11
  • 4
    alias mkdirs=mkdir -p
    – dr jerry
    Jul 24, 2018 at 19:23
  • Is there a way to set permissions recursively too? Jul 15, 2021 at 12:03
73
mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"
0
26

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.

2
  • 11
    You may want to explain what {...,...} is in bash and why what your doing makes sense. A short explanation of the brace expansion would be beneficial to other users. A "you can do this" and get "this" leaves a bit to the imagination. Dec 22, 2017 at 5:43
  • I agree with @DavidC.Rankin. This answer is perfect IMHO, but it needs explaining what the bracket notation actually does.
    – Delali
    Dec 9, 2018 at 15:44
0
mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8
1
  • This will just create 8 sub-directories in newDir/.
    – csabinho
    Oct 24, 2019 at 22:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.