2

So I just have learned about bash expansion...and it's cool :) now I want to create some good plans for next year (just as an example).

I can't figure out how you can create folders and create some files within each folder in one pass... Is this possible or I need to get into each directory and repeat everything manually?

sean@COMMODORE:~$ mkdir plans && cd plans && mkdir 2021-CW{01..52}
sean@COMMODORE:~/plans$ ls
2021-CW01  2021-CW05  2021-CW09  2021-CW13  2021-CW17  2021-CW21  2021-CW25  2021-CW29  2021-CW33  2021-CW37  2021-CW41  2021-CW45  2021-CW49
2021-CW02  2021-CW06  2021-CW10  2021-CW14  2021-CW18  2021-CW22  2021-CW26  2021-CW30  2021-CW34  2021-CW38  2021-CW42  2021-CW46  2021-CW50
2021-CW03  2021-CW07  2021-CW11  2021-CW15  2021-CW19  2021-CW23  2021-CW27  2021-CW31  2021-CW35  2021-CW39  2021-CW43  2021-CW47  2021-CW51
2021-CW04  2021-CW08  2021-CW12  2021-CW16  2021-CW20  2021-CW24  2021-CW28  2021-CW32  2021-CW36  2021-CW40  2021-CW44  2021-CW48  2021-CW52
sean@COMMODORE:~/plans$ cd 2021-CW01
sean@COMMODORE:~/plans/2021-CW01$ touch {work,sport,shopping,music}.txt
sean@COMMODORE:~/plans/2021-CW01$ ls
music.txt  shopping.txt  sport.txt  work.txt
sean@COMMODORE:~/plans/2021-CW01$

2 Answers 2

4

You can simplify the first mkdir to just one command using -p to create the parent directory too:

mkdir -p plans/2021-CW{01..52}

and then use just a single touch to create the files in all directories

touch plans/2021-CW{01..52}/{work,sport,shopping,music}.txt
$ ls plans/2021-CW*
plans/2021-CW01:
music.txt  shopping.txt  sport.txt  work.txt

plans/2021-CW02:
music.txt  shopping.txt  sport.txt  work.txt

...

plans/2021-CW52:
music.txt  shopping.txt  sport.txt  work.txt
2

I wrote a script which you can use to do this :

#!/bin/bash

mkdir -p plans/2021-CW{01..52} && cd plans

for d in */
do
    if [ -d "${d}" ] ; then 
        cd ${d} ; touch {work,sport,shopping,music}.txt ; cd ..
    fi
done

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.