Last Updated: February 25, 2016
·
616
· designerfoo

Bash Script To Create A Directory within a Child Directory of a Parent Directory Supplied

The Bash Script

#!/bin/bash

#Script to create directory within a child directory of a parent directory supplied.

if [ ! "$1" = "" -a ! "$2" = "" ]; then
    for dd in $(ls "$2");
    do
    if [ -d "$2$dd" ]; then
        mkdir -p --verbose $2$dd\$1;
    else
        echo 'Dir Not Created';
    fi;
    done;
else
echo "*********Usage*******";
echo "createDir <DIRNAME> <PARENTDIR>";
fi;

The Explanation

So, I came across a situation where I had to create one or more child directories within a parent directory, so I thought I did go with bash and come up with a simple and fast way of getting it done.

The script takes 2 parameters. The first one is the name of the directory to be created, the second parameter is the path of the parent directory.

The script checks both parameters, loops through the parent directory and on finding a directory, creates the directory required within it.

So for e.g. we have a directory called Cities, within which we have say about 5 different directories called, NYC, London, Bombay, San Francisco and Paris. And within each of these 5 directories I want to create a directory called "Restaurants", the script usage will be as follows:

$ ./createDir.sh Restaurants /PathTo/Cities

This will create the following structure:

/PathTo/Cities/NYC/Restaurants/
/PathTo/Cities/London/Restaurants/
/PathTo/Cities/Bombay/Restaurants/
/PathTo/Cities/San Francisco/Restaurants/
/PathTo/Cities/Paris/Restaurants/

Download as Github Gist

You can download this script/gist from github