Setting the wallpaper on macOS

When trying to set up a bash script to update the wallpaper on my Mac, I ran into this wired issue. Basically, the wallpapers of each space / desktop are really smart and change independently. So after some frantic Internet searches, I found out the following:

TL;DR

function background {
    IMG=$1
    osascript -e "tell application \"System Events\" to set picture of every desktop to \"${IMG}\""
    sqlite3 ~/Library/Application\ Support/Dock/desktoppicture.db "update data set value = '${IMG}'"
    killall Dock
}

Let's hope this post will save someone like me a few searches and head-scratches 😅. By the way, I use Unsplash to download the fresh backgrounds, and have amassed
a nice little collection of suitable pictures.