Search code examples
bashalgorithmrecursionmkdir

Creating recursive folders with a linux bash script


I've asked this once before, and it was marked as it needs more details. Well here it is in great detail.

Goal is to have a script that creates folders as follows:

main

  • After creating a single folder called 'main' inside that folder it will create 6 'a' folders named with numbers and letters respectively "1a 2a 3a 4a 5a 6a"

  • After creating those 6 'a' folders, it's going to create 6 'b' folders inside EACH of those 6 'a' folders. So each 'a' folder will contain "1b 2b 3b 4b 5b 6b"

  • After creating those 6 'b' folders, it's going to create 6 'c' folders in each of those 6 'b' folders. So, they will all contain the folders "1c 2c 3c 4c 5c 6c"

  • After that, it will create 6 'd' folders in each of 'c' folders. So the 'c' folders will contain "1d 2d 3d 4d 5d 6d"

  • After that, it will create 6 'e' folders in each of 'd' folders. So the 'd' folders will contain "1e 2e 3e 4e 5e 6e"

  • After that, it will create 6 'f' folders in each of 'e' folders. So the 'e' folders will contain "1f 2f 3f 4f 5f 6f"

  • All 'f' folders will be empty

The end result should be:

  1. One 'main' folder that has 6 'a' folders
  2. All 'a' folders should have 6 'b' folders
  3. All 'b' folders should have 6 'c' folders
  4. All 'c' folders should have 6 'd' folders
  5. All 'd' folders should have 6 'e' folders
  6. All 'e' folders should have 6 'f' folders
  7. All 'f' folders must remain empty

This should be a linux shell script of course.

I don't have the code to post, I've been trying with for loops where i is from 1 to 6 and it creates a folder named that. If you really want the code I wrote for this problem I'll gladly paste the 50000+ lines of mkdir that I wrote months ago. This problem recently came to my mind and I wanted to see if anyone else could find a solution, because nothing I tried worked.


Solution

  • How about

    #!/bin/bash
    
    for a in 1 2 3 4 5 6
    do
        for b in 1 2 3 4 5 6
        do
            for c in 1 2 3 4 5 6
            do
                for d in 1 2 3 4 5 6
                do
                    for e in 1 2 3 4 5 6
                    do
                        for f in 1 2 3 4 5 6
                        do
                            mkdir -p main/a$a/b$b/c$c/d$d/e$e/f$f
                        done
                    done
                done
            done
        done
    done
    

    but I'm sure you can improve it...