With a small bash script, it is possible to randomly select an image from a
directory and change the current GNOME wallpaper to that image. It's easy to
forget just how powerful bash can be; more than just a simple command shell,
bash has a whole host of features that make it well-suited for even complex
programming tasks.
To begin this hack, you need to have a directory full of wallpapers somewhere.
Assume this directory is located at /home/foo/Images/Wallpapers/. This script
will take an image from that directory and set it as the current wallpaper.
Here's the first part of the script:
#!/bin/bash
export DIR='/home/foo/Images/Wallpapers/'
export NUMBER=$RANDOM
export TOTAL=0
The first line is a standard piece of code that says which program should be
used to run the script (in this case bash). After this line is the
location of the directory containing your images, stored in the $DIR
variable for future use. Next, you store a random number, which is generated by
the built-in variable named $RANDOM. You also set $TOTAL to
0 to begin with; this variable stores the total number of images in the
directory.
After this initial code, you need to create a loop that counts the number of images
in the directory using the output of the ls command. Because this script doesn't
check file types, it is important that you store only images in this directory.
Here is the loop:
for f in `ls $DIR`
do
let "TOTAL += 1"
done
let "NUMBER %= TOTAL"
The line let "NUMBER %= TOTAL" is the part that actually selects which image will be
used. This line divides the randomly generated number by the number of images in the
directory and stores the remainder of this division in the $NUMBER variable. If
you're wondering how this works, the remainder must be between 0 and 1, minus the
number of images, and because in the next part the script starts counting from 0, it
is possible for any image to be selected with this method.
The final part of the script simply counts through each image to see if it is the
one that was selected. When it finds the correct image, it modifies the GConf setting
that stores the filename of the wallpaper using the gconftool command (this might be
gconftool-2 on some systems). Nautilus notices this change immediately and updates
the wallpaper. So, here's the final script:
#!/bin/bash
export DIR='/home/adam/Images/Wallpapers/'
export NUMBER=$RANDOM
export TOTAL=0
for f in `ls $DIR`
do
let "TOTAL += 1"
done
let "NUMBER %= TOTAL"
export CURRENT=0
for f in `ls $DIR`
do
if [ $CURRENT = $NUMBER ]
then
/usr/bin/gconftool-2 -t string -s /desktop/gnome/background/picture_filename
$DIR/$f
break
fi
let "CURRENT += 1"
done
Save the script somewhere convenient such as /home/foo/setbg.sh. Also make it executable
by running the following in a terminal:
foo@bar:~$ chmod +x setbg.sh
Now when you run this script your wallpaper will be changed.
No comments:
Post a Comment