Home > front end >  How do I create 100 files with 1 random number in each of them and give them permissions based on th
How do I create 100 files with 1 random number in each of them and give them permissions based on th

Time:12-16

I need to create a bash script that creates 100 files with random numbers in them. I tried to do it using:

for i in {1..100}; do $RANDOM > RANDOM.txt

I don't know if that's the correct way to do it. And then I need to give the files reading writing and execution permissions based on the number inside the file. No idea how to do that. I tried using:

if [ $i%2==0 ]
then
echo chmod  rw $RANDOM.txt

but that doesn't seem to work

CodePudding user response:

First, you need to echo the random number, not use it as a command.

Second, if you want to use the same random number as the filename and content, you need to save it to a variable. Otherwise you'll get a different number each time you write $RANDOM.

Third, that's not how you do arithmetic and conditions inside [], any shell scripting tutorial should show the correct way. You can also use a bash arithmetic expression with (( expression )).

#!/bin/bash
for i in {1..100}
do
    r=$RANDOM
    echo "$r" > "$r.txt"
    if (( i % 2 == 0 ))
    then
        chmod  rw "$r.txt"
    fi
done

CodePudding user response:

I think it'd be simplest to use chmod with octal permissions, like 0777 for rwxrwxrwx etc.

Example:

#!/bin/bash

for i in {1..100}; do
    rnd=$RANDOM                     # pick a random number
    (( perm = rnd % 512 ))          # make it in the range [0, 512) (0000-0777 oct)
    octperm=$(printf "o" $perm)   # convert to octal

    file=$rnd.txt                   # not sure if you meant to name it after the number
    echo $rnd > $file

    chmod $octperm $file            # chmod with octal number
done

Excerpt of files:

-r-xrw--wx 1 ted users   5 15 dec 17.53 6515.txt
---x-wxrwx 1 ted users   5 15 dec 17.53 6751.txt
-rwx-w--w- 1 ted users   5 15 dec 17.53 8146.txt
-rw-r----- 1 ted users   5 15 dec 17.53 8608.txt
--w--w---x 1 ted users   5 15 dec 17.53 8849.txt
--wx----wx 1 ted users   5 15 dec 17.53 8899.txt
--wxrwx-wx 1 ted users   5 15 dec 17.53 8955.txt
-rw-r-xrw- 1 ted users   5 15 dec 17.53 9134.txt
...
  • Related