I thought it would be fun to write a simple and small bash script which randomly chooses a wallpaper from a given directory of a set of wallpaper images. The code is as follows.
#!/bin/bash
# simple script to choose random image from
# Wallpaper directory and set it as desktop background
# cd into Wallpaper dir
cd /home/user/Pictures/Wallpapers
# using nano time mod # of imgs in Wallpapers (+1 b/c awk fields start at ind 1)
# to provide a semi-random field number for the awk statement
RAND=$(($(date +%N) % $(ls -h | wc -l) + 1))
IMG=$(ls -h | awk -v r=$RAND 'BEGIN{FS = "\n"; RS = ""} {print $r}')
# change the desktop with the img file provided from the awk statement
# (the way to set the background is system dependent but the gist is the same)
gsettings set org.gnome.desktop.background picture-uri "file:///home/user/Pictures/Wallpapers/$IMG"
This is really just a small, fun project, but I am almost certain I am not doing this the most efficient way, so any feedback would be great.
1 Answer 1
Let's consider ls
bad practice, and allow me to introduce a different method to solve your issue all together. Find every file in the directory, /home/user/Pictures/Wallpapers, perform a random sort on it and then grab the first result.
find /home/user/Pictures/Wallpapers -type f | sort -R | head -1
-R, --random-sort
shuffle, but group identical keys. See shuf(1)