How to change desktop background from command line in Unity?
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.
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
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 , <[email protected]>
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.