0

Hey guys I have a small script for making a parent folder with n number of subfolders.

I'm basing this off of the command mkdir -p parentFolder/{"Folder 1", "Folder 2",...}.

Running this by writing it out like above will create the following folder structure:

parentFolder
|-Folder 1
|-Folder 2
|-Folder 3
#!/bin/bash
#Takes two arguments for the name of your parent folder 
#and how many subfolders you want

function createFolderAndSubfolders {
folderName="$1"
numberOfSubfolders="$2"
subFolderName="subFolder"

buildString="$folderName/{"

for (( i=1; i<=$numberOfSubfolders; i++ ))
do
        if [[ $i -ne $numberOfSubfolders ]]; then
           buildString+="\"$subFolderName $i\","
        else
           # If last number in loop, don't add comma
           buildString+="\"$subFolderName $i\""
        fi
done
buildString+="}"
#This should make an example string like: 'parentFolder/{"subFolder 1","subFolder 2"}'

#Create parent and sub folders
mkdir -p "$buildString"
}

When I run it through with this string concatenation I'm getting the parent folder but only a single subfolder instead of what happens when typing it out manually.

parentFolder
|-{"subFolder 1","subFolder 2"}

I have also tried single quotes for escaping the double quotes to the same effect.

Am I missing anything that could prevent this from working?

Joshua
  • 51
  • 1
  • 1
  • 2
  • `eval mkdir -p parentFolder/subFolder{1..$numberOfSubfolders}` might help but take a look at [Why should eval be avoided in Bash, and what should I use instead?](https://stackoverflow.com/q/17529220/3776858) – Cyrus Feb 22 '20 at 06:51

1 Answers1

0

mkdir -p "$buildString" is supplying one really long argument to the command and all operators like the { are escaped and treated as characters.

You should simply call mkdir for each folder directly? ie.

for (( i=1; i<=$numberOfSubfolders; i++ ))
do
        mkdir -p "$subFolderName $i"
done

Even if your method can be made to work it would leave you open to possible problems such as if the subFolderName has a double quote in?, ie: ./myscript.sh "folder \" name" 10

If you really want to build a list, don't use the {} operator as this is simply expaneded by bash as extra arguments for mkdir anyway.

ie:

buildString=""
for (( i=1; i<=$numberOfSubfolders; i++ ))
do
    buildString+=" \"$subFolderName $i\""
done
mkdir -p $buildString

And finally, bash wildcard expressions already support what you're trying to do.

mkdir New\ Folder\ {0..10}
Geoffrey
  • 10,843
  • 3
  • 33
  • 46