Bash script to make directories recursive with depth and size
Hello,
I was wondering how one makes a bash script given a depth and a size/layer to make directories in directories and so on. For example I pass depth = 3 and size = 2 than the output needs to look like: Code:
├── dir1 Code:
for (( g=1; g<=$size; g++ )) |
If you're using bash you could use sequence expressions:
Code:
mkdir -p dir{1..2}/dir{3..6}/dir{7..14}/ |
That is not really what I want, I want to use a variable depth, in your code the depth is 3, but I want a script where I can pass for example the depth as $1.
|
Could you define your own bash function so that it can call itself recursively to create directories up to a certain depth?
|
Well I don't know, But if so it would look like something like this I guess:
Code:
|
Just look at it differently... It is nothing but a two dimensional array, with dimensions of size, depth.
You are just sequentially indexing all elements in the array - so using an i,j index, two nested loops would visit each directory... The number given to the given directory is just i + j * size. The name of the directory is just a counter used to count the creation of a directory... No recursion required. |
Here is a basic recursion function.
Code:
a () { Code:
a 1 3 |
No recursion is necessary.
Think of it as a two dimensional array, and that you are examining each (i,j) identified element. The name of the directory could just be a counter accumulating the number of elements visited. If you get clever, you can construct the path of directory names you want, then just use the -p option of mkdir to create the entire string (hint - use 1 offset index computations to the i,j conversion). It actually sounds like a homework assignment... |
Thank you for your answers but I don't understand it fully, first of all this is not homework, yes I am a student studying Apllied Informatics but in school we don't see any bash scripting unfortunately, this is for my own goal of learning bash and Linux. So you are saying I should use a 2d array but how am I going to make directory on each level with the 2d array?
Code:
|
Revised my function, deleted the original script by accident...:/
Code:
# args: depth size |
mkdir -p can create not only a single dir, but also its parent (recursively) - see man mkdir.
So you only need to generate the list of subdirs (of the given depth) and mkdir -p <list> will do it in one. |
All times are GMT -5. The time now is 09:04 AM. |