Sam
Sam

Reputation: 2347

Issues with making basic tree structure in bash script

I'm just trying to make a simple bash script to make a tree structure and I cannot spot where my logic is wrong. As of now, the script will make it to the second depth but only fills out the first folder in it. Can anyone spot my error(s)?

Thanks

#!/bin/bash

create(){

 directory=$1

 for((j=0; j < depth; j++)); do


  for x in ${directory[@]}; do

    temp=( )

    for((i=0; i < breadth; i++)); do

        mkdir $x/$i 

        temp=($temp $x/$i)

    done    

  done  

    directory=($temp)

 done



}

breadth=3
depth=2

direc=(tree)

create $direc

Upvotes: 0

Views: 1092

Answers (2)

NJITGeniusCS288
NJITGeniusCS288

Reputation: 1

#!/bin/bash

#The program expects three arguments: dir, depth, breadth in that order

directory=$1
depth=$2
breadth=$3


create()
{
    for((j=0; j < depth; j++))
    do
        for x in ${directory[@]}
    do
            temp=( )
            for((i=0; i < breadth; i++))
        do
                mkdir -p $x/$i
                #echo $x/$i
                temp=(${temp[@]} $x/$i)
            done
        done
        directory=(${temp[@]})
    done
}

create

Upvotes: 0

travisbartley
travisbartley

Reputation: 349

The problem is that mkdir cannot create multiple levels of directories without the --parents (-p) switch. So on the line:

mkdir $x/$i

it cannot create $x/$i because $x does not exist. Try making this change:

create(){
    directory=$1
    for((j=0; j < depth; j++)); do
        for x in ${directory[@]}; do
            temp=( )
            for((i=0; i < breadth; i++)); do
                mkdir -p $x/$i
                temp=($temp $x/$i)
            done
        done
        directory=($temp)
    done
}


breadth=3
depth=2

direc=(tree)

create $direc

edited based on lotusphp's more elegant solution

Upvotes: 2

Related Questions