63

I have a script that updates my desktop background every day with the NASA APOD. Since upgrading to 11.10, that script stopped working, presumably because I'm using gconftool-2 to actually update the desktop background. Is there a new way to do this under Unity?

82

Both Unity and Gnome Shell (Gnome 3) use GSettings now instead of GConf. So in Unity and Gnome Shell you can use the command-line tool gsettings for that. Like gconftool, it lets you get or set an individual key.

You can get the current URI of the background image as follows:

gsettings get org.gnome.desktop.background picture-uri
'file:///home/serrano/Pictures/x.jpg'

And set the background URI as follows (which will immediately update your desktop background):

gsettings set org.gnome.desktop.background picture-uri file:///home/serrano/Pictures/y.jpg

Notice that you must prepend the URI with "file://" for this to work (unlike with gconftool).

In order to make your script work with both Gnome 2 and Shell/Unity, you can let it do a Gnome version check first:

gnome-session --version

That will return the version of Gnome. If the version number starts with 3, then gsettings can be used. If it returns a version starting with 2, let your script use gconftool instead.

  • I used this command in Ubuntu 12.04 and system is crashed – YumYumYum Sep 5 '13 at 14:26
  • 2
    @YumYumYum: It's highly unusual that the above commands will crash your system, unless there's something else going on in your system. – Serrano Sep 5 '13 at 17:22
  • You can add Cinnamon to the list of Desktop Environment using gsettings ;) – MrVaykadji Jan 7 '14 at 18:36
  • Notice that you must prepend the URI with "file://" for this to work (unlike with gconftool). <-- This is important! I didn't find this mentioned explicitly anywhere else. – Tom Mar 30 '14 at 19:52
  • 2
    This is fine for the current user logged in. I'd like to know how to programatically change wallpaper of another user! I did try sudo --user=<username> gsettings ... but that failed. – kaiwan May 10 '14 at 7:57
12

This code randomly changes the wallpaper from a given directory.

#!/bin/bash

DIR="/home/indra/Pictures/wallpapers"
PIC=$(ls $DIR/* | shuf -n1)
gsettings set org.gnome.desktop.background picture-uri "file://$PIC"

Save this script and edit your with the command "crontab -e" (it launches an editor where you put this line at the end of the file):

*/1     *     *     *     *         /bin/bash /path/to/script.sh
  • 1
    The wallpaper directory must contain only wallpaper files and no directory. – loxaxs Jan 26 '17 at 10:58
  • gsettings won't work from cron, however. you need to set the DBUS_SESSION_BUS_ADDRESS environment variable in order for gsettings to work. You can do that by adding these two lines before gsettings (lines separate by semicolons:) PID=$(pgrep gnome-session); export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$PID/environ|cut -d= -f2-); – willbradley Jan 13 '18 at 0:25
6

Introduction

This answer is an edit of the original answer. As I've progressed in my Ubuntu and Linux studies, I've discovered a variety of approaches and deepened my understanding of how setting a background works in Ubuntu. This answer is my attempt to document as best as possible what I've learned thus far, and is done in hopes that this material can be useful for others.

The important part is that to set background for Unity desktop from command line, you can use

gsettings set org.gnome.desktop.background picture-uri 'file:///home/JohnDoe/Pictures/cool_wallpaper.jpg'

Setting background in Unity vs bare X desktop

The way Unity works is such that there is bare X desktop below, and above there is Unity's desktop window (which in fact is a special instance of Nautilus's window , the default file manager of Ubuntu ). Thus, when you call

gsettings set org.gnome.desktop.background picture-uri 'file:///home/JohnDoe/Pictures/cool_wallpaper.jpg'

that sets background for that special Nautilus window. When you disable desktop icons with

gsettings set org.gnome.desktop.background show-desktop-icons false

that will kill the Nautilus desktop and show you bare-bones X desktop. For the bare-bone X desktop you can use feh program. Particularly, this command:

feh --bg-scale /home/JohnDoe/Pictures/cool_wallpaper.jpg

There's also GUI alternative to that, nitrogen. The feh and nitrogen approaches can be used with desktops other than Unity, such as openbox or blackbox. The gsettings approach can be used with Unity or other GNOME-based desktop.

Disecting the gsettings command

What exactly does gsettings command do ? Well, first of all, there exists dconf database of settings for each user, which is intended as replacement for deprecated GConf, and it is accessible via either dconf command or gsettings. In particular , we're dealing here with org.gnome.desktop.background schema and one of its keys, picture-uri.

URI, that file:///home/JohnDoe/Pictures/cool_wallpaper.png, actually stands for Uniform Resource Identifier, which originally was created for internet usage, but there is file URI scheme , which is what we see here. What's cool about URI is that it gives byte-encoded path if you use a non-english locale, for example with my Chinese desktop, I have following URI for my backgroun: 'file:///home/xieerqi/%E5%9B%BE%E7%89%87/Wallpapers/moon_moon.jpg'

Scripting with gsettings

Of course, writing out the command each time is tedious and one can use a little bit of scripting magic. For instance, here's what I have set in my ~/.bashrc so that I can change background at will:

change_background() {
    FILE="'file://$(readlink -e "$1" )'" 
    if [ "$FILE" != "'file://'" ] 
    then
        gsettings set org.gnome.desktop.background picture-uri "$FILE" 
    else
        echo "File doesn't exist" 
    fi 
} 

This function can be called with absolute path such as

change_background /home/JohnDoe/Pictures/cool_wallpaper.jpg

or with relative path from current working directory

change_background Pictures/cool_wallpaper.jpg

It also performs a check if file exists and resolves symlinks. This can be used in a shell script or as standalone function for daily use.

Of course, this is not the only way. Python has an API for Gio ( which is the main library behind gsettings ). I've written a gsettings_get and gsettings_set functions, which were quite useful for other projects such as Launcher List Indicator. In case of setting a background, it can also be used and I've used it just recently for this question. Here's a simplified version of that same approach:

#!/usr/bin/env python3
"""
Author: Serg Kolo , <1047481448@qq.com>
Date: December, 21,2016
Purpose: script for setting wallpaper, the pythonic way
Written for: https://askubuntu.com/q/66914/295286
"""
from gi.repository import Gio
import os,sys,random

def gsettings_set(schema, path, key, value):
    """Set value of gsettings schema"""
    if path is None:
        gsettings = Gio.Settings.new(schema)
    else:
        gsettings = Gio.Settings.new_with_path(schema, path)
    if isinstance(value, list):
        return gsettings.set_strv(key, value)
    if isinstance(value, int):
        return gsettings.set_int(key, value)
    if isinstance(value,str): 
        return gsettings.set_string(key,value)

def error_and_exit(message):
    sys.stderr.write(message + "\n")
    sys.exit(1)

def main():
    gschema='org.gnome.desktop.background'
    key='picture-uri'
    if len(sys.argv) != 2:
        error_and_exit('>>> Path to a file is required')
    if not os.path.isfile(sys.argv[1]):
        error_and_exit('>>> Path "' + sys.argv[1] + \
                       '" isn\'t a file or file doesn\'t exit')
    full_path = os.path.abspath(sys.argv[1])
    uri = Gio.File.new_for_path(full_path).get_uri()
    gsettings_set(gschema,None,key,uri)


if __name__ == '__main__': main()

Of course, same rules for scripts apply here too: ensure it is made executable with chmod +x set_wallpaper.py and store it in (preferrably) ~/bin folder. Usage is simple: ./set_wallpaper.py Picture/cool_image.py Source code of this script is also available on my GitHub repository with many other scripts,too.

1

Thanks to Serrano's awesome answer, I was able to write this script which I use as part of my new machine setup scripts to set a black background:

#! /bin/bash
SRC_URI="https://i.imgur.com/uomkVIL.png"
FNAME="/home/$USER/Pictures/black.png"
wget "$SRC_URI" -O "$FNAME"
gsettings set org.gnome.desktop.background picture-uri "$FNAME"
1

Also you can use this:

dconf write "/org/gnome/desktop/background/picture-uri" "'file:///home/YOUR_USER/bg.png'"

protected by Community Aug 23 '16 at 6:55

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.