11 March 2011

Change wallpaper periodically in Ubuntu

Thanks to UbuntuForums.org, I made a simple cron job changing desktop wallpaper depending on time.

crontab

SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
@hourly /share/scripts/bash/change_wallpaper.sh

change_wallpaper.sh

#!/bin/bash -
# Get the pid of nautilus
nautilus_pid=$(pgrep -u $LOGNAME -n nautilus)
# If nautilus isn't running, just exit silently
if [ -z "$nautilus_pid" ]; then
    exit 0
fi
# Grab the DBUS_SESSION_BUS_ADDRESS variable from nautilus's environment
eval $(tr '\0' '\n' < /proc/$nautilus_pid/environ | grep '^DBUS_SESSION_BUS_ADDRESS=')
# Check that we actually found it
if [ -z "$DBUS_SESSION_BUS_ADDRESS" ]; then
    echo "Failed to find bus address" >&2
    exit 1
fi
# export it so that child processes will inherit it
export DBUS_SESSION_BUS_ADDRESS
HOUR=$(date +%H)
PICDIR="/usr/share/backgrounds/"
#echo "HOUR: $HOUR"
#echo "PICDIR: $PICDIR"
case $HOUR in
21|22|23|00|01|02|03|04|05|06)
/usr/bin/gconftool-2 --type string --set  /desktop/gnome/background/picture_filename $PICDIR"NATURE-ZenLizard.png"
;;
12|13|14|15|16|17|18|19|20)
/usr/bin/gconftool-2 --type string --set  /desktop/gnome/background/picture_filename $PICDIR"Fern_by_aalex04.jpg" 
;;
09|10|11)
/usr/bin/gconftool-2 --type string --set  /desktop/gnome/background/picture_filename $PICDIR"Bon-Echo_wallpaper.jpg"
;;
*)
/usr/bin/gconftool-2 --type string --set  /desktop/gnome/background/picture_filename $PICDIR"Ropey_Photo_by_Bob_Farrell.jpg"
;;
esac

I wonder, why it didn't work without DBUS_SESSION_BUS_ADDRESS detection. However, it works now. I'd be glad, if it helps someone.