Search code examples
arraysbashrandomshls

Execute random file from a folder in a bash script


I'm newbies with bash scripts, so please, be indulgent ;-) !!!

I would like to read php files randomly in a pre-defined folder (there are 30 php files in this folder).

My current script:

#!/bin/sh
curl "/myfolder/myfile.php" &
exit 0

With my research i've already done, i've found some examples but i'm not sure of anything with my little skills.

I know i must use an "for ls" and then do something like "echo $ ((1 + RANDOM% 30))", but i'm not sure !

Could you help me please?


Solution

  • You can just use the "sort" tool with the option "-R" to sort randomly. In a given directory you can run

    ls -1 /etc/ | sort -R | head -1
    

    to pick one file randomly out of all. The "etc" directory is just an example.

    Your code should then look like this:

    curl `ls -1 /my_folder/ | sort -R | head -1` &
    

    But I don't understand how you call "curl" with a file? This will not execute the PHP code in the file.