How to pick random images so that newer ones are picked in Linux

I have a bash script on a headless Linux server that takes a filename as a parameter and displays a full screen image of the provided image on a ray.

Users can upload images to a shared folder. I want a random picture of this folder to be fetched every few seconds and displayed. But not completely random. I want to make a new (according to the time of its creation) photograph, the more likely it is shown. This way, all old images are also displayed, but newer ones will be displayed more often.

Is there a way (using bash and standard unix tools) to select a random image from a folder (no subfolders and all files end with ".jpg" suffix) and take their age into account, so the likelihood of choosing an image is higher than it is higher?

It would be better if this probability were not linear: while the second matters when the picture is only a few seconds or minutes, it does not need to have a huge difference between the picture, which is 2 hours or one, which is equal to 2 hours and 15 minutes ...

+3


source to share


1 answer


This random selection of jpg files with files created or modified in the last hour selected three times more often, and files created or modified in the last six hours are selected twice as often as older files:

{
    find . -name '*.jpg' -mmin -60
    find . -name '*.jpg' -mmin -360
    find . -name '*.jpg'
} | shuf -n1

      

How it works

shuf -n1

randomly selects one line from the lines it specifies on standard input. The commands find

provide standard input. The files modified in the last 60 minutes -mmin -60

are listed by all three commands find

. Those that have changed in the last 360 minutes -mmin -360

are listed by two of the three teams. The last command find

contains a list of all jpg files. This is what gives the variation in probability.



You can adjust both the number of commands find

and the cutoff time according to your preference.

Improvement

The above works as long as there are no newlines in the filenames. To deal with this possibility, use null-terminated lists:

{
    find . -name '*.jpg' -mmin -60 -print0
    find . -name '*.jpg' -mmin 360 -print0
    find . -name '*.jpg' -print0
} | shuf -z -n1

      

+4


source







All Articles