How can I create nonexistent subdirectories recursively using Bash?
Solution 1
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
mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"
Solution 3
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.
Related videos on Youtube
Topher Fangio
Founder/CEO of Profoundry LLC in Abilene, Texas. Core team member of Angular Material. Building awesome things with Angular, Ruby on Rails, PostgreSQL, and vim (the best damn editor on the planet). Check out my mad skillz!
Updated on October 28, 2021Comments
-
Topher Fangio over 2 years
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"
-
Ciro Santilli OurBigBook.com almost 8 years
-
-
Topher Fangio over 14 years@bmargulies - Holy crap that was way simpler than I thought =P
-
Russia Must Remove Putin over 9 yearsUpvoted because you're a deletionist. Oops, already did about a year ago!
-
David C. Rankin over 6 yearsYou 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. -
TheKitMurkit about 6 yearsIt doesn't work if user has no right to read one of intermittent folders
-
dr jerry almost 6 years
alias mkdirs=mkdir -p
-
Delali over 5 yearsI agree with @DavidC.Rankin. This answer is perfect IMHO, but it needs explaining what the bracket notation actually does.
-
csabinho over 4 yearsThis will just create 8 sub-directories in
newDir/
. -
Saeed Neamati almost 3 yearsIs there a way to set permissions recursively too?