Issue at hand
I am trying to write a bash script to quickly create a directory structure. This is an attempt to learn more about manipulating arrays, variables, and using loops. My script works to check for the existence of a directory then create folders. The issue I am having is creating a third level of directories within the first two layers.
Goals
I want to be able to write a bash script that will create a directory structure of ~/a/a/a, ~/a/a/b, ~/a/a/c,...,~/a/z/z
for example. This should be flexible to so I could use any kind of array or variable that would be suitable.
Here is what I have worked out so far:
#!/bin/bash
array_0=(one two three four five)
array_1=(x y z)
if [ ! -d "directory" ]; then
mkdir directory
fi
for array_0 in "${array_0[@]}"
do
mkdir ~/directory/$array_0/
done
if [ -d "~/directory/$array_0/" ]; then
for array_1 in "${array_0[@]}"
do
mkdir ~/directory/$array_0/$array_1
done
fi
exit 0
Problem
The error I get is mkdir: cannot create directory '/home/user/directory/one/x' : No such file or directory
Other attempts at this script allow me to create ~/directory
and ~/directory/one, ~/directory/two,..., ~/directory/five
without fail but not the next level i.e /directory/one/x
and etc.
How can I script the creation of this directory structure? Is this possible using arrays or is there another method?
For reference I tried to implement this post and elements from this post but I have not had any luck creating the directory structure that I want.
1 Answer 1
You could use a nested array loop, like this
#!/bin/bash
array_0=(one two three four five)
array_1=(x y z)
for a0 in "${array_0[@]}"
do
for a1 in "${array_1[@]}"
do
mkdir -p "$HOME/web/$a0/$a1"
done
done
Or, if you don't mind avoiding the use of arrays but using expansion lists instead, this single command will do much the same thing:
mkdir -p ~/web/{one,two,three,four,five}/{x,y,z}
-
I did not know you could do this in a one-liner. I just learned of arrays and thought that they would help. Your
mkdir -p ~/{one,two,three,four,five}/{x,y,z}
example works great. Thank you, I was making this too complicated.kemotep– kemotep2018年02月26日 20:48:22 +00:00Commented Feb 26, 2018 at 20:48 -
@kemotep there's definitely a time and place for arrays so don't worry about this not necessarily being one of them.Chris Davies– Chris Davies2018年02月26日 21:40:04 +00:00Commented Feb 26, 2018 at 21:40
mkdir -p
will create all required directories. For example you can domkdir -p one/two/three/four/five
and it will create all the directories required (if they don't exist) in order to makefive
for array_0 in "${array_0[@]}"
Oops.x
inarray_1[0]
, but the first timearray_1
is referenced after the assignment is whenarray_1
is used to loop over the values ofarray_0
. So no, it doesn't look like that script would try to createdirectory/one/x
, or otherwise lead to that error...