user10336264
user10336264

Reputation:

Nesting a case statement within a for loop

I'm trying to follow the instructions below in order to create one directory containing four subdirectories inside, each of these latter with five new empty files:

  1. Create a directory with the name of the first positional parameter (choose whatever name you want).

  2. Use a for loop to do the following:

    2.1. Within the directory, create four subdirectories with these names: rent, utilities, groceries, other.

    2.2. Within the for loop, use case statements to determine which subdirectory is currently being handled in the loop. You will need 4 cases.

    2.3. Within each case, use a for loop to create 5 empty files with the touch command. Each subdirectory must have its 5 files inside.

So far, I have created a directory and several subdirectories at once, each of them with a specific name, as you can see in my code:

mkdir $1
for folder in $1; do 
mkdir -p $1/{Rent,Utilities,Groceries,Other}
done

However, I'm stuck in the following step (2.2.), and I don't know how to continue from here.

Any ideas?

Upvotes: 0

Views: 2022

Answers (1)

John Kugelman
John Kugelman

Reputation: 361730

As I read it, this is what 2.1 and 2.2 are asking for:

for folder in rent utilities groceries other; do 
    mkdir "$1/$folder"

    case $folder in
        rent)
            ...
            ;;
        utilities)
            ...
            ;;
        groceries)
            ...
            ;;
        other)
            ...
            ;;
    esac
done

I've left the cases blank for you to fill out.

For what it's worth, I would never code a script this way. Having a case statement inside a for loop is an anti-pattern. The loop really adds no value. If this weren't an assignment I would code it differently:

mkdir "$1"

# Populate rent/ directory.
mkdir "$1"/rent
touch "$1"/rent/...

# Populate utilities/ directory.
mkdir "$1"/utilities
touch "$1"/utilities/...

# Populate groceries/ directory.
mkdir "$1"/groceries
touch "$1"/groceries/...

# Populate other/ directory.
mkdir "$1"/other
touch "$1"/other/...

Upvotes: 2

Related Questions