Sub Directories in sub directory using loop

On my CentOS machine, I need to create a main directory inside which I will have a few sub directories and, inside them, some subsubdirectories.

Something like:

main_directory->sub1,sub2,sb3..
sub1->subsub1,subsub2,subsub3..
sub2->subsub1,subsub2,subsub3..
sub3->subsub1,subsub2,subsub3..

I want to create this kind of directory structure using a loop and using mkdir inside the loop. Also, I want the user to input all these directories and sub directories and sub sub directory names. How can I do this?

Answer

It is not limited to a fixed number of dirs, so if you want to create 2, 3 or pass your entire life creating directories and sub-directories, until causing a explosion, here is the script:

#!/bin/bash
enter_recursive(){
while true; do
        echo "Please enter the name of the directory you want to create inside $PWD or type _up to exit the directory"
        read dir
        [ "$dir" = "_up" ] && return
        mkdir "$dir"
        echo -n "Do you want to create subdirectories in $PWD/${dir}? (y/n)"
        read -n1 yn
        echo
        if [ "$yn" == "y" ]; then
                cd "$dir"
                enter_recursive
                cd ..
        fi

done
}

enter_recursive

Leave a Reply

Your email address will not be published. Required fields are marked *