Random wallpapers for Nitrogen (Linux)
Here I am sharing my script which randomly selects picture file from the defined folder and applies this file as a wallpaper. This script is written for one of the most popular programs of this kind in Linux - nitrogen.
When I decided to make this script, I wanted it to do the following:
- Randomly select file as a wallpaper.
- Has minimum writing operations on the disk.
Here is what I came with.
I keep my wallpaper files in the ~/wallpaper/ folder and they are all JPG.
“nitrogen” config file
At first, I looked into the nitrogen configuration files. On my system they are located here: ~/.config/nitrogen/ and there are two files there: nitrogen.cfg and bg-saved.cfg. And I am interested in the latter.
bg-saved.cfg looks like this on my system:
1# For the display 0 (default)
2[xin_0]
3# Path to the image file
4file=~/wallpapers/current_bg_image.jpg
5# Mode of wallpaper (I am using "scaled"). E.g. 4 is "stretched".
6mode=3
7# Background color
8bgcolor=#000000
9
10# For the display 1
11[xin_1]
12file=~/wallpapers/current_bg_image.jpg
13mode=3
14bgcolor=#000000As you can see, I am using the same background on both displays (default laptop display and some external one if I use it).
The script
The trick here is that I want nitrogen configuration file from above not to change, so I came up with the use of symbolic link as a reference on the actually selected file.
1#!/bin/sh
2
3# It is needed to make nitrogen work correctly
4export DISPLAY=":0"
5
6# Defining the directory with wallpapers
7BG_DIR=$HOME/wallpapers
8
9# Getting date of the creation of the current_bg_image.jpg (used in the nitrogen configuration)
10BG_IMAGE_DATE=$(ls -l --time-style=full-iso "${BG_DIR}"/current_bg_image.jpg | awk '{print $6}')
11
12# Getting current date
13TODAY=$(date -I)
14
15# Checking, if dates differ, then we randomly select new wallpaper
16if [ "${BG_IMAGE_DATE}" != "${TODAY}" ]
17then
18 # Removing of the old symlink
19 [ -f "${BG_DIR}"/current_bg_image.jpg ] && rm "${BG_DIR}"/current_bg_image.jpg
20
21 # Feeding random generator with the date in seconds (UNIX time)
22 RANDOM=$$$(date +%s)
23
24 # Generating list of all wallpapers in the directory
25 BG_LIST=("${BG_DIR}"/*.jpg)
26
27 # Counting total number of files
28 BG_NUM=$(ls -1 "${BG_DIR}" | wc -l)
29
30 # Randomly select some number from the total number of wallpapers
31 SELECTED_BG=$(( $RANDOM % ${BG_NUM} ))
32
33 # Creating new symbolic link to the selected wallpaper with the name "current_bg_image.jpg"
34 ln -s "${BG_LIST[$SELECTED_BG]}" "${BG_DIR}"/current_bg_image.jpg
35
36 # refreshing wallpaper image
37 nitrogen --restore > /dev/null 2>&1 &
38fiCron
I want my wallpaper picture to change every day. But because I use laptop, and it might be off in a particular point of time, I use cron task which runs every hour from 7 AM till 8 PM every day.
This guarantees that when I open laptop at any time of day, my wallpaper will eventually change.