Recurse directories and return random file

I have a nice program to change the background but I want it to operate on subdirectories as well.

# Script to randomly set Background from files in a directory
while true;do

# Directory Containing Pictures
DIR="/home/pc/Pictures"

# Internal Field Separator set to newline, so file names with
# spaces do not break our script.
IFS='
'

# Command to Select a random jpg file from directory
PIC=$(ls $DIR/*.jpg | shuf -n1)

# Command to set Background Image
gsettings set org.mate.background picture-filename $PIC

# specify how long to wait in seconds between changes
sleep 600

done

Try

find $DIR -iname "*.jpg"

in lieu of the ls command.

Hm. To prevent find from running too often - disk intensive to list an entire big directory tree -- how about:

DIR="/home/pc/Pictures"

while true
do
        find "$DIR" -type f -name '*.jpg' | shuf | while read PIC
        do
                gsettings set org.mate.background picture-filename "$PIC"
                sleep 600
        done
done

Instead of taking the first from the randomized list then throwing the rest away, it will use the entire random-order list.

1 Like

Many thanks to you both. All working very nicely now.

1 Like

If you have ImageMagick installed you could use it to identify those images that are too small for the backgroud (eg with a width < 1200 pixels)

IR="/home/pc/Pictures"

while true
do
        find "$DIR" -type f -name '*.jpg' | shuf | while read PIC
        do
                (($(identify -format "%w" "$PIC") < 1200)) && continue
                gsettings set org.mate.background picture-filename "$PIC"
                sleep 600
        done
done