Update Mac OS X desktop background from a script

I have a shell script that gets run by a cron job that updates a jpeg. The desktop background on my external monitor is set to this same file. However, Mac OS X does not automatically refresh the desktop background when the file is updated.

How do I force the desktop background to be updated from the script?


A proper way (without using something else to call your script) would be to add the following line to your shell script:

osascript -e 'tell Application "Finder"' -e 'set the desktop picture to {"NAME OF STARTUP DRIVE:PATH:TO:PICTURE.jpg"} as alias' -e 'end tell'

Note: The path uses colons instead of a / and you must name the hard drive.

A really odd alternative more for giggles, is a massive kludge of a workaround is to add the following line to your shell script run by cron:

killall Dock

This will kill the Dock, which when it restarts (automatically) will refresh your desktop background. Downsides? Your open application dock icons will re-order (if the app icons aren't already saved a position in your dock) and any minimized windows will unminimize. So if you don't use those features, it's fine.


My previous answer to this sucked, so here's a better one.

I use a shell script and an Automator workflow to do this. The shell script downloads the image I want, saves it somewhere, and echos the full path to the image (that's the important part). The Automator workflow then looks something like this:

[run shell script ~/bin/getAPOD.sh] -> [Set the Desktop Picture]

That "Set the Desktop Picture" action, as far as I can tell, came with Automator.

I then have a crontab entry that looks like this:

* 4 * * * /usr/bin/open /Users/myuser/bin/APODset.app

If you'd like I can post the script, the Automator workflow, whatever.


Here's the final applescript I'm using:

tell application "System Events"
    set myfolder to folder "foo" of the pictures folder
    tell desktop 2 to set picture to file "empty.jpeg" of myfolder as alias
    tell desktop 2 to set picture to file "bar.jpeg" of myfolder as alias
end tell

This is passed to osascript from the shell (actually ruby) script that updates the jpeg.

The previously discussed issue of the background not updating if the new path is the same as the current path (which was still a problem with Chealion's answer) is hacked-around by temporarily switching to "empty.jpeg". This is annoying as the transition is jerky but it beats having to restart the Finder/Dock.

I'm using the System Events application because the Apple examples do too.