2
\$\begingroup\$

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.

chicks
2,8593 gold badges18 silver badges30 bronze badges
asked Aug 13, 2020 at 5:43
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Why you shouldn't parse ls.

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

Sort man page

 -R, --random-sort
 shuffle, but group identical keys. See shuf(1)
answered Aug 13, 2020 at 13:42
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.