arraysbashmkdir

How can I use an array to create subdirectories using mkdir in bash?


I am trying to create a number of directories and subdirectories in one single command (ie avoiding for loops) like so:

mkdir -p {20..30}/{1..5}

This works no problem, and creates 10 directories, and inside each of them, it creates another 5. All good.

However I'd like to replace the subdirectories with an array, but this doesn't work as I expect.

For example, if I create:

tru=(1 2 3 4 5)

and do:

mkdir -p {20..30}/${tru[@]}

this is interpreted as

mkdir -p {20..30}/1 2 3 4 5

and only one subdirectory is created with name "1".

How can I make mkdir interpret my new array in a similar way to how it's doing with {1..5}?


Solution

  • Well, if you're accepting hacky answers:

    Taking for a test drive:

    $ echo mkdir -p sub{1..3}/{$(printf "%s," "${tru[@]}")}
    mkdir -p sub1/{1,2,3,4,5,} sub2/{1,2,3,4,5,} sub3/{1,2,3,4,5,}
    
    $ eval mkdir -p sub{1..3}/{$(printf "%s," "${tru[@]}")}
    
    $ find . -type d | sort -V
    .
    ./sub1
    ./sub1/1
    ./sub1/2
    ./sub1/3
    ./sub1/4
    ./sub1/5
    ./sub2
    ./sub2/1
    ./sub2/2
    ./sub2/3
    ./sub2/4
    ./sub2/5
    ./sub3
    ./sub3/1
    ./sub3/2
    ./sub3/3
    ./sub3/4
    ./sub3/5