0

Recently, in university, we started working with Linux and Bash. We have a task where we have to create 5 directories with the names Directory1, Directory2, and so on. In each directory we have to create 10 files with one random number inside.

I started like this, but I don't know what to do next:

#!/bin/bash 
for i in {1..5}
do
    mkdir "Directory${i}"
done

Can you please help me?

1
  • Which version of Ubuntu are you using?
    – user68186
    Dec 1, 2020 at 13:33

2 Answers 2

5

Actually, I think that you should do your own homework, and your question includes some of the knowledge you need.

  • You understand loops.
  • You must do a loop inside your first loop.
  • You should investigate how to get a random number.

Despite this, here you have a oneliner that fits your requirements, if I haven't misunderstood you:

for i in {1..5}; do mkdir "Directory${i}"; for j in {1..10}; do echo $RANDOM > "Directory${i}/File${j}"; done; done
4

Here is another one-line solution that uses brace expansion for the creation of the directories and files and a for-loop to generate random numbers and add them to each file (thanks @pLumo for the suggestion):

mkdir -p Directory{1..5} && for f in Directory{1..5}/{1..10}.txt; do echo "$RANDOM" > "$f"; done

The -p option tells mkdir to create the any parent directories of the path you give it (not relevant here) and also tells it not to fail if the directory already exists (so you can run the same command again).

0

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.