Create the directory structure using mkdir and touch

I am learning Unix online and i came across this question to create a hierarchical structure. I have created the directories using mkdir command but I am stuck while creating the files inside directory.

Directory Structure to be created

My command for creating directories is

mkdir -p mydir/{colors/{basic,blended},shape,animals/{mammals,reptiles}}

Solution 1:

Here's two ways to do it. There's more, but the concept would be the same: either extending what you have, or iterating over a list and breaking each list item into parts.

Long way to do it

There's nothing special that needs to be done with touch. Simply extend the same arguments that you had for mkdir command to include files.

bash-4.3$ mkdir -p mydir/{colors/{basic,blended},shape,animals/{mammals,reptiles}}
bash-4.3$ tree mydir
mydir
├── animals
│   ├── mammals
│   └── reptiles
├── colors
│   ├── basic
│   └── blended
└── shape

7 directories, 0 files
bash-4.3$ touch mydir/{colors/{basic/{red,blue,green},blended/{yellow,orange,pink}},shape/{circle,square,cube},animals/{mammals/{platipus,bat,dog},reptiles/{snakes,crocodile,lizard}}}
bash-4.3$ tree mydir
mydir
├── animals
│   ├── mammals
│   │   ├── bat
│   │   ├── dog
│   │   └── platipus
│   └── reptiles
│       ├── crocodile
│       ├── lizard
│       └── snakes
├── colors
│   ├── basic
│   │   ├── blue
│   │   ├── green
│   │   └── red
│   └── blended
│       ├── orange
│       ├── pink
│       └── yellow
└── shape
    ├── circle
    ├── cube
    └── square

Short way

If you observe, all of your directories have files to create. Thus what we can do is create list of items( effectively a bash array ) and iterate over them, with using mkdir with suffix removal and then touch. Like this:

bash-4.3$ arr=( mydir/{colors/{basic/{red,blue,green},blended/{yellow,orange,pink}},shape/{circle,square,cube},animals/{mammals/{platipus,bat,dog},reptiles/{snakes,crocodile,lizard}}} )
bash-4.3$ for i in "${arr[@]}"; do  mkdir -p "${i%/*}" && touch "$i"; done
bash-4.3$ tree mydir
mydir
├── animals
│   ├── mammals
│   │   ├── bat
│   │   ├── dog
│   │   └── platipus
│   └── reptiles
│       ├── crocodile
│       ├── lizard
│       └── snakes
├── colors
│   ├── basic
│   │   ├── blue
│   │   ├── green
│   │   └── red
│   └── blended
│       ├── orange
│       ├── pink
│       └── yellow
└── shape
    ├── circle
    ├── cube
    └── square

7 directories, 15 files

Side note: if you have spaces in any file or directory name, ensure that you single or double quote those items, e.g.:

arr=( mydir/{'with space',without_space/{file1,file2}} )

See also.