18 December 2014

Randomly changing the desktop wallpaper via crontab

Here is a simple way to organize a random desktop wallpaper by means of crontab.

We'll use feh application here. Let's put the following code into ~/bin/wallpaper-change file:

#!/bin/bash -
# Pick and set a random wallpaper

: ${DISPLAY:=":0"}

if [ $# -lt 1 ]; then
  echo >&2 "No source directory specified"
  exit 1
fi

dir="$1"
if [[ ! -d "$dir" ]]; then
  echo >&2 "Directory $dir doesn't exist"
  exit 1
fi

find $dir/ -maxdepth 1 -type f | sort -R | tail -1 | while read f
do
  feh --bg-fill "$f" &
done
(Don't forget to make it executable.)

Now we can adjust the crontab, e.g.:

DISPLAY=:0
@hourly ~/bin/wallpaper-change ~/Pictures/wallpapers

Note, setting the DISPLAY environment variable is crucial.