12

I have a folder named music where inside there is all of the artist folders. Is there a way to create these folders: 1. Albums, 2. EP, 3. Singles, 4. Live in all the artist folders with a command?

0
12

Sure, execute this in the music folder where the artist folders are:

for artist in */; do
   for folder in "1. Albums" "2. EP" "3. Singles" "4. Live"; do
      mkdir "$artist/$folder"
   done
done

You can execute this on your CLI, or you can make it a shell script by adding #!/bin/sh as the first line and saving it in a file. Don't forget to make the file executable.

As for what it does: it iterates over all directories (*/) within the current directory, then for each of these directories, iterates over the desired subfolder (the second for), and then makes the desired (relative) subfolder.

1
  • 1
    Oh it's beautiful, this will go down in history ;-) – Steve Sep 16 '19 at 13:34
18

You may want to put on your {curly} braces for this one

For the sake of this argument we will pretend ./music doesn't exist

In your base directory for ./music we will use the -p command to create sub-directories where needed and the curly braces will be used to create a small array

The command -p is short for parent, if it's easier to remember you may use --parent instead

mkdir -p ./music/{"1. Albums","2. EP","3. Singles","4. Live"}

If you wish to play around with this you may, for example

mkdir -p ./folder/prefix{a{1/only,2,3},b,c}suffix/more{z,y,x}

You have nested expressions, you may insert the braces in to the middle of a string and you can also allow the subdirectory to follow suit, and you can be specific with your sub directories for a particular array

I suggest you make a file somewhere where you can make your own templates with such commands and give them descriptions

Visit this page for more information https://www.linuxjournal.com/content/bash-brace-expansion and https://www.linux.com/tutorials/all-about-curly-braces-bash/

3
  • 5
    Personally I like this answer better, because it doesn't need you to think as a programmer. I rarely use the curly brace method, but it is much more elegant. – jawtheshark Sep 16 '19 at 9:17
  • 6
    OP wants the 4 subdir placed inside each subdir itself of music, so the correct arg to mkdir would be ./music/*/{"1. Albums","2. EP","3. Singles","4. Live"} – joH1 Sep 17 '19 at 8:22
  • 1
    FYI, -p is the short form of --parent. – Amedee Van Gasse Sep 17 '19 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy