Home > OS >  Unix file making with one randomly chosen file in a directory
Unix file making with one randomly chosen file in a directory

Time:11-22

I’m having a hard time figuring out why my script will make files, but not add the text into the files it creates in the “eggs” directory. Can anyone help me figure out what I have wrong in my code? Or offer suggestions? I’ve tried single > and double >> for the text appending to the file but it doesn’t. It just leaves the files blank.

Edit:

file=0

RandomEgg=$(( RANDOM % 10 ))
cd eggs

while [ $file -lt 10 ]
do
    touch "egg$file"
    file=$(( file  1 ))
done

for files in $(ls eggs)
do
    if [ $file -eq $RandomEgg ]
then
    echo 'Found it!' > egg$file
else
    echo 'Not Here!' > egg$file
    fi
done

CodePudding user response:

In bash, the script could be reduced into

cd eggs || exit
RandomEgg=$(( RANDOM % 10 ))
for ((i = 0; i < 10;   i)); do
    if ((i == RandomEgg)); then
        echo 'Found it!'
    else
        echo 'Not Here!'
    fi > egg$i
done

or,

cd eggs || exit
RandomEgg=$(( RANDOM % 10 ))
msg=('Not Here!' 'Found it!')
for ((i = 0; i < 10;   i)); do echo "${msg[i == RandomEgg]}" > egg$i; done

CodePudding user response:

Change the second loop to:

for files in egg*
do
    if [ $files = "egg$RandomEgg" ]
    then
        echo 'Found it!' > $files
    else
        echo 'Not Here!' > $files
    fi
done

You don't need to use ls to list the files, just use a wildcard. You were also listing the wrong directory -- the files were created in the current directory, not the eggs subdirectory.

You need to use $files as the filename, not egg$file, since that's the variable from this for loop.

You must use = to compare strings, not -eq. -eq is for numbers.

  • Related