-1

I wrote a program that creates a bunch of directories based on the depth and breadth. There is 1 parameter which is the directory i want to make all the directories in. The problem is that it only makes the directories in the directory where this script exists. Is there anyway I can choose where the script creates the directories?

#!/bin/sh
depth=2
breadth=5

open=($1)
for((i=0; i<depth; i++)); do
    temp_open=()
    for x in "${open[@]}"; do
        temp=()
        for((j=0; j<breadth; j++)); do
            mkdir -p $i/$j
            temp=(${temp[@]} "$i/$j")
        done
        temp_open=(${temp[@]})
    done
    open=(${temp_open[@]})
done
Karan K
  • 21
  • 7
  • 3
    The simple fix would be to just put `cd "$1" || exit` as the first line, so that the rest of the script runs in that directory – that other guy Sep 27 '16 at 23:09
  • 3
    There's a whole lot that's not right here, btw. Consider running this code through http://shellcheck.net/ – Charles Duffy Sep 27 '16 at 23:12
  • Also, the `#!/bin/sh` shebang here is incorrect, since POSIX sh doesn't support arrays. It probably should be `#!/bin/bash`, or (for your lack of quoting to be correct) `#!/bin/zsh`. – Charles Duffy Sep 27 '16 at 23:13
  • You are not using the variable x to do anything. Why is that? –  Sep 27 '16 at 23:19
  • actually the prefered and most portable shebang is [`#!/usr/bin/env bash`](http://stackoverflow.com/questions/10376206/what-is-the-preferred-bash-shebang) –  Sep 28 '16 at 00:24
  • Hey i am just using x to loop through open. Also i fixed the #!/bin.bash. @char – Karan K Sep 28 '16 at 00:26
  • @CharlesDuffy it seems to work fine, there are no errors that pop up – Karan K Sep 28 '16 at 00:26
  • 1
    @KaranVansia, "seems to work" isn't particularly authoritative, unless you're trying interesting enough use cases to trigger bugs. Try working with directory names with spaces in them. – Charles Duffy Sep 28 '16 at 00:28
  • ...or passing an argument with spaces, for that matter. – Charles Duffy Sep 28 '16 at 00:29
  • @JarrodRoberson the first time the open array only has 1 value which is the directory path. The mkdir will create files in that directory. Then open value will be set equal to temp, then it will create directories in each directory that was created previously. – Karan K Sep 28 '16 at 00:30
  • @CharlesDuffy I will try that, thank you! – Karan K Sep 28 '16 at 00:32

1 Answers1

1

Define this variable:

 mydir="/directory/to/make/dirs"

Change mkdir -p $i/$j to this:

 mkdir -p "$mydir/$i/$j"