You are not logged in.

#1 2009-02-03 18:46:44

moljac024
Member
From: Serbia
Registered: 2008-01-29
Posts: 2,676

A script for setting a random wallpaper

I've cooked up this small bash script for changing the wallpaper to a random one from a specified directory (it is recursive)

The script tries to be smart in determining whether the wallpaper should be scaled, centered or tiled.
Just configure it and try it out.

Anyway, here goes:

#!/bin/bash
# Random wallpaper setter, by moljac024
#-------------------------------------------------------------------------------------
# Configuration

# Wallpaper directory
wpDir="$HOME/Wallpapers"

# Wallpaper list path
wpList=$HOME/.wallpaper-list

# Folders to be skipped, you can put as many as you like
#wpSkip=("Dir1/" "Dir2/")

# Scale images that have a lower resolution than that of the screen (yes or no)
scaleLowerRes="yes"
#scaleLowerRes="no"

# Screen resolution
resWidth=1280
resHeight=800

# Command for tiling the wallpaper
cmdTile="feh --bg-tile"
#cmdTile="nitrogen --set-tiled --save"OA
#cmdTile="xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-style -s 2 && xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s"
#cmdTile="gconftool-2 -t str --set /desktop/gnome/background/picture_options "wallpaper" -t str --set /desktop/gnome/background/picture_filename"

# Command for scaling the wallpaper
cmdScale="feh --bg-scale"
#cmdScale="nitrogen --set-scaled --save"
#cmdScale="xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-style -s 3 && xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s"
#cmdScale="gconftool-2 -t str --set /desktop/gnome/background/picture_options "zoom" -t str --set /desktop/gnome/background/picture_filename"

# Command for centering the wallpaper
cmdCenter="feh --bg-center"
#cmdCenter="nitrogen --set-centered --save"
#cmdCenter="xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-style -s 1 && xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s"
#cmdCenter="gconftool-2 -t str --set /desktop/gnome/background/picture_options "centered" -t str --set /desktop/gnome/background/picture_filename"

# End of configuration
#-------------------------------------------------------------------------------------

setTiled ()
{
`$cmdTile "$1"`
if [ "$?" = "0" ]; then
echo "Wallpaper tiled."
else
echo "Wallpaper not set!"
exit 1
fi
}

setScaled ()
{
`$cmdScale "$1"`
if [ "$?" = "0" ]; then
echo "Wallpaper scaled."
else
echo "Wallpaper not set!"
exit 1
fi
}

setCentered ()
{
`$cmdCenter "$1"`
if [ "$?" = "0" ]; then
echo "Wallpaper centered."
else
echo "Wallpaper not set!"
exit 1
fi
}

createList ()
{
# Go to the wallpaper directory
cd "$wpDir"

# Load the list of pictures to a variable
wpDirList=`(find . -regex ".*\([jJ][pP][gG]\|[jJ][pP][eE][gG]\|[gG][iI][fF]\|[pP][nN][gG]\|[bB][mM][pP]\)$"  -type f)`

# Save the list to disk
if [[ ( -w "$wpList" ) ]]; then
echo -n "$wpDirList" > "$wpList"
# Filter out unwanted folders
if [[ "$dontSkip" == "false" ]]; then
for dir in "${wpSkip[@]}" 
do
   grep -Ev "$dir" "$wpList" > ~/.wallpapers-tmpr; mv ~/.wallpapers-tmpr "$wpList"
done
fi
# Output result
echo "Wallpaper list saved."
else
echo "Can't write wallpaper list, aborting!"
exit 1
fi
}

getImage ()
{
# Count number of pictures in the wallpaper list by counting number of lines.
# Check if the wallpaper list exists, is not empty and we have read persmission on it
if [[ ( -s "$wpList" && -f "$wpList" ) && -r "$wpList" ]]
    then
    wpListNumber=$(wc -l < "$wpList")
    else
    echo "Can't read wallpaper list, aborting!";
    exit 1
fi

# Counter for bad entries in wallpaper list
badMax=100

while true; do

# Get a seed for the random number generator from /dev/urandom
SEED=$(head -1 /dev/urandom | od -N 1 | awk '{ print $2 }')
RANDOM=$SEED

# Find a random line number in the wallpaper list
# Random number from 1..n.
#r=$((RANDOM % $wpListNumber + 1))
r=$(echo $RANDOM%"$wpListNumber"+1 | bc)

# Print what the line number is
# Print the r'th line.
imgPath=`sed -n "$r{p;q;}" "$wpList"`
# #./ crops that substring but it doesn't matter if it left there
wpPath="${wpDir}${imgPath#./}"

# Check if the chosen file exists
if [ -f "$wpPath" ]; then
    break
else
    echo -e ""$wpPath": doesn't exist!\n"
    badMax=$(( $badMax - 1 ))
    if [ "$badMax" == "0" ]; then
    echo "Too many non-valid entries found in wallpaper list, aborting!"
    exit 1
        else echo "Choosing new image..."
    fi
continue
fi
done

# Calculate size and aspect for chosen image and print out information
imgHeight=$(identify -format "%h" "$wpPath")
imgWidth=$(identify -format "%w" "$wpPath")
imgAspect=$(echo "scale=1; "$imgWidth"/"$imgHeight"" | bc)
echo -e "Image: "$wpPath"\n"
echo -e "Resolution: "$imgWidth"x"$imgHeight""
echo -e "Aspect: "$imgAspect":1\n"
}

setWallpaper ()
{
# Calculate resolution aspect ratio
resAspect=$(echo "scale=1; "$resWidth"/"$resHeight"" | bc)

# If the image is smaller than the resolution and is not a tile then scale it, otherwise look at aspect
if [[ ("$scaleLowerRes" == "yes") && ( "$imgAspect" != "1.0" && ("$imgWidth" -lt "$resWidth" || "$imgHeight" -lt "$resHeight") ) ]]
then
setScaled "$wpPath"
else
case $imgAspect in
1.0)
setTiled "$wpPath"
;;
1.5 | 1.6 | 1.7 | 1.8)
if [[ "$resAspect" < "1.5" ]]; then
setCentered "$wpPath"
else
setScaled "$wpPath"
fi
;;
*)
if [[ "$resAspect" < "1.5" ]]; then
setScaled "$wpPath"
else
setCentered "$wpPath"
fi
;;
esac
fi
}

checkConfig ()
{
# Initial errors
errorsPresent="no"
dontSkip="false"
# Check if all variables are set
if [[ !( ( -n "$wpDir" ) && ( -n "$wpList" ) && ( -n "$resWidth" ) && ( -n "$resHeight" ) && ( -n "$scaleLowerRes" ) && ( -n "$cmdTile" ) && ( -n "$cmdScale" ) && ( -n "$cmdCenter" ) ) ]]
then
echo -e "\nOne or more options not set, aborting!"
exit 1
fi

# Check if there is a trailing backslash in the wallpaper directory
spDir=`echo -n "$wpDir" | tail -c -1`
if [[ !( "$spDir" == "/" ) ]]
then
wpDir=""$wpDir"/"
fi

# Check if there is read permission on wallpaper directory and if it is a directory
if [[ !( ( -r "$wpDir" ) && ( -d "$wpDir" ) ) ]]
then
echo "Can't read wallpaper directory!"
errorsPresent="yes"
fi

# Check if the specified wallpaper list is a regular file and not a directory
touch "$wpList" &> /dev/null
if [[ ( -d "$wpList" ) ]]
then
echo "Specified wallpaper list is a directory, not a file!"
errorsPresent="yes"
fi

# Check if variables are set correctly
if [[ !( "$scaleLowerRes" == "yes" || "$scaleLowerRes"  == "no" ) ]]
then
echo "Specified option for scaling the wallpaper is not valid!"
errorsPresent="yes"
fi

if $(echo ""$resWidth"" | grep [^0-9] &>/dev/null)
then
echo "Specified resolution width is not a number!"
errorsPresent="yes"
fi

if $(echo ""$resHeight"" | grep [^0-9] &>/dev/null)
then
echo "Specified resolution height is not a number!"
errorsPresent="yes"
fi

# Check if any of the tests failed
if [[ "$errorsPresent" == "yes" ]]
then
echo -e "\nOne or more errors found, aborting!"
exit 1
fi
}

ignoreWPSkip()
{
dontSkip="true"
}

printUsage ()
{
echo -e "Invalid command line argument(s)!\nUsage:\n"
echo -e "`basename "$0"` [options]\n"
echo -e "Options:\n"
echo -e "-s  | --set       \tSet a wallpaper without updating the list"
echo -e "-u  | --update    \tUpdate the list without setting a wallpaper"
echo -e "-ua | --update-all\tUpdate the list without setting a wallpaper, but don't skip any folders"
echo -e "-su | --set-update\tUpdate the list and set a wallpaper"
exit 1
}

if [ "$#" == "1" ]; then
case "$1" in
"-s" | "--set")
checkConfig
getImage
setWallpaper
exit 0
;;
"-u" | "--update")
checkConfig
createList
exit 0
;;
"-ua" | "--update-all")
checkConfig
ignoreWPSkip
createList
exit 0
;;
"-su" | "--set-update")
checkConfig
createList
getImage
setWallpaper
exit 0
;;
*)
printUsage
exit 1
;;
esac
else
printUsage
exit 1
fi

Last edited by moljac024 (2009-09-14 21:02:13)


The day Microsoft makes a product that doesn't suck, is the day they make a vacuum cleaner.
--------------------------------------------------------------------------------------------------------------
But if they tell you that I've lost my mind, maybe it's not gone just a little hard to find...

Offline

#2 2009-02-22 20:37:55

CheesyBeef
Member
Registered: 2008-06-04
Posts: 190

Re: A script for setting a random wallpaper

Thank you!  This is just what I wanted.  My script I created based on the wiki entry: http://wiki.archlinux.org/index.php/Feh didn't work when I tried to run it from the Openbox menu.  Maybe it was the way it was set up, but this worked perfectly once I remember to issue an option after the script (ie. --set-update).

One thing for users wanting to use this script, make sure you have bc and imagemagick installed, or the script will return "command not found" errors around lines 128-130 in the script:

pacman -Sy imagemagick bc

I really think this would be a great contribution to that wiki page smile

Last edited by CheesyBeef (2009-02-22 21:41:13)

Offline

#3 2009-02-22 21:37:03

moljac024
Member
From: Serbia
Registered: 2008-01-29
Posts: 2,676

Re: A script for setting a random wallpaper

Oh yeah, forgot to mention that.
And it's imagemagick not imageshack wink


The day Microsoft makes a product that doesn't suck, is the day they make a vacuum cleaner.
--------------------------------------------------------------------------------------------------------------
But if they tell you that I've lost my mind, maybe it's not gone just a little hard to find...

Offline

#4 2009-02-22 21:40:56

CheesyBeef
Member
Registered: 2008-06-04
Posts: 190

Re: A script for setting a random wallpaper

Haha sorry, I use imageshack as my main image host, so that's probably why i put that smile

Offline

#5 2009-03-23 02:02:06

Joe_Arch
Member
Registered: 2008-11-27
Posts: 67

Re: A script for setting a random wallpaper

This is great! It seems to work like a charm.

However, my .xinitrc-fu is weak. I'm trying to stick this in at startup, but I can't figure out how to have it run without root permissions.  After I use chmod on the script, it doesn't need sudo to run but it gives a "Can't write wallpaper list, aborting" message. I can't figure out why it needs root permissions to create the wallpaper-list, since I have that in my home directory.


Anyone know how to stick this script into .xinitrc properly? Or change it so it doesn't need root permissions?

Offline

#6 2009-09-12 20:38:43

bense
Member
From: South Carolina
Registered: 2009-09-12
Posts: 1

Re: A script for setting a random wallpaper

Man this is exactly what I was wanting.  A script that I can stick in my .xinitrc and have it run and surprise me everytime I startup my X server.

I didn't want to have some matt daemon running in the background either.

Offline

#7 2009-09-14 20:05:58

zen3
Member
From: Greece
Registered: 2009-09-02
Posts: 30

Re: A script for setting a random wallpaper

What shall I put in this?

# Wallpaper list path
wpList=$HOME/.wallpaper-lis


ffc

Offline

#8 2009-09-14 20:58:18

moljac024
Member
From: Serbia
Registered: 2008-01-29
Posts: 2,676

Re: A script for setting a random wallpaper

zen3 wrote:

What shall I put in this?

# Wallpaper list path
wpList=$HOME/.wallpaper-lis

Just a file where you want the wallpaper list to be saved

EDIT: I changed the script a bit, so i've edited the first post if someone is interested, but there's not much difference

Last edited by moljac024 (2009-09-14 21:03:43)


The day Microsoft makes a product that doesn't suck, is the day they make a vacuum cleaner.
--------------------------------------------------------------------------------------------------------------
But if they tell you that I've lost my mind, maybe it's not gone just a little hard to find...

Offline

#9 2009-09-14 21:19:25

scj
Member
From: Sweden
Registered: 2007-09-23
Posts: 158

Re: A script for setting a random wallpaper

I did something similar a couple of months ago, but instead of attempting to be clever and guessing what the background image is supposed to be, I just write it in the filename. Since some pictures just end up being too bright (or whatever) when used as a background to a urxvt terminal, I added some extra parameters for setting gamma, brightness, tint and the direction the image should be rendered. It relies on hsetroot for actually rendering the picture.

#!/usr/bin/python
# set-background
import sys, os, string, re

patterns =  [ (re.compile("t-([a-f\d]+)"),  lambda x: "-tint \#" + x)
            , (re.compile("b-([\d]+)"),     lambda x: "-brightness -0." + x)
            , (re.compile("g-([\d]+)"),     lambda x: "-gamma "+ x)
            , (re.compile("f-(v|h|d)"),     lambda x: "-flip" + x)
            ]

def buildCommand(file):
  output = ["hsetroot"]
  output.append("-" + (string.split(file,".")[-2]))
  output.append(file)
  for token in string.split(file,".")[1:-2]:
    for (pat,f) in patterns:
      if pat.match(token):
        output.append( f(pat.findall(token)[0]))
  return string.join(output)

print buildCommand(img)
os.system(buildCommand(img))

# vim:set et:

So for instance, an image with the name background.t-704214.f-v.full.jpg would be rendered as a stretched image, flipped vertically with a sepia tint. The files are required to be in the following format NAME.(MODIFIER.)*TYPE.SUFFIX, where the the order and number of modifiers are unimportant. The gamma values are somewhat unintuitive, but I guess you'll just have to play around with it to get it right.

And to randomize the whole thing, I just used the following script in my .xinitrc to randomly pick a image from a folder.

#!/bin/bash

bg_folder="$HOME/.backgrounds";
pics=($(ls $bg_folder))

let "n = $RANDOM % ${#pics[@]}"
(cd $bg_folder; set-background ${pics[$n]})

Offline

#10 2009-09-14 22:03:06

bernarcher
Forum Fellow
From: Germany
Registered: 2009-02-17
Posts: 2,281

Re: A script for setting a random wallpaper

There are some fine scripts here, but I used the simple script freom the feh wiki to randomly change my openbox background every 30 minutes:
http://wiki.archlinux.org/index.php/Feh … ound_Image

To accomplish this I did set up a special folder containing fitting wallpapers only. Thus I don't have top bother about sizes and display strategies. It is a one-time
convert <infile> -resize 1280x1024 <outfile>
task for each if necessary at all.


To know or not to know ...
... the questions remain forever.

Offline

#11 2009-09-15 11:02:44

zen3
Member
From: Greece
Registered: 2009-09-02
Posts: 30

Re: A script for setting a random wallpaper

wpList=$HOME/.wallpaper-list

And what am I supposed to replace with it?

I replaced wpList=$HOME/.wallpaper-list -> touch /home/zen/wallpaper/.list ad wpList=$/home/zen/wallpapers/.list but get this error -> Can't read wallpaper list, aborting!


ffc

Offline

#12 2009-09-15 11:09:24

Rasi
Member
From: Germany
Registered: 2007-08-14
Posts: 1,914
Website

Re: A script for setting a random wallpaper

zen3 wrote:

wpList=$HOME/.wallpaper-list

And what am I supposed to replace with it?

I replaced wpList=$HOME/.wallpaper-list -> touch /home/zen/wallpaper/.list ad wpList=$/home/zen/wallpapers/.list but get this error -> Can't read wallpaper list, aborting!

Thats because $HOME is a placeholder for /home/YOUR_USERNAME. either use the vriable that was already set and simply edit the filename at the end OR remove the $ from your line smile

Last edited by Rasi (2009-09-15 11:09:55)


He hoped and prayed that there wasn't an afterlife. Then he realized there was a contradiction involved here and merely hoped that there wasn't an afterlife.

Douglas Adams

Offline

#13 2009-09-15 11:15:32

moljac024
Member
From: Serbia
Registered: 2008-01-29
Posts: 2,676

Re: A script for setting a random wallpaper

Rasi wrote:
zen3 wrote:

wpList=$HOME/.wallpaper-list

And what am I supposed to replace with it?

I replaced wpList=$HOME/.wallpaper-list -> touch /home/zen/wallpaper/.list ad wpList=$/home/zen/wallpapers/.list but get this error -> Can't read wallpaper list, aborting!

Thats because $HOME is a placeholder for /home/YOUR_USERNAME. either use the vriable that was already set and simply edit the filename at the end OR remove the $ from your line smile

You can just put "wpList=$HOME/wallpapers/.list" then


The day Microsoft makes a product that doesn't suck, is the day they make a vacuum cleaner.
--------------------------------------------------------------------------------------------------------------
But if they tell you that I've lost my mind, maybe it's not gone just a little hard to find...

Offline

#14 2009-09-15 11:50:36

zen3
Member
From: Greece
Registered: 2009-09-02
Posts: 30

Re: A script for setting a random wallpaper

Did it.
Thank you.


ffc

Offline

#15 2010-02-14 11:25:51

chili
Member
Registered: 2008-04-18
Posts: 5

Re: A script for setting a random wallpaper

kudos for this script

Offline

#16 2010-03-21 14:48:53

pie86
Member
Registered: 2009-09-06
Posts: 78

Re: A script for setting a random wallpaper

EDIT: doesn't work! The first time background is changed but then gconf-editor goes into confusion. Don't know why...I solved adding the script to Gnome Session manager and with a while + sleep loop.

------
this workaround is needed is you want to run the script from cron and change gnome wallpaper.

#workarond

eval `dbus-launch --sh-syntax`

export DBUS_SESSION_BUS_ADDRESS
export DBUS_SESSION_BUS_PID

for details see here: http://stackoverflow.com/questions/2576 … -for-gconf

bye
Pietro

Last edited by pie86 (2010-03-22 17:38:41)

Offline

#17 2010-10-28 10:55:48

eNTi
Member
Registered: 2006-04-30
Posts: 109

Re: A script for setting a random wallpaper

thanks, works great.

Offline

#18 2010-10-28 12:32:45

72linus
Member
From: gordonsville,va
Registered: 2009-03-14
Posts: 144
Website

Re: A script for setting a random wallpaper

I made a script that randomly changes background with any WM/DM
and put it in Chrysalis a debian livecd
http://linux.softpedia.com/get/System/O … 3472.shtml

will grab the script, etc if you want?/

Offline

#19 2010-10-28 15:13:26

Daenyth
Forum Fellow
From: Boston, MA
Registered: 2008-02-24
Posts: 1,244

Re: A script for setting a random wallpaper

Here's my similar script to contrast: http://github.com/Daenyth/dotfiles/blob … in/rwpaper

Offline

#20 2010-11-02 17:50:28

eNTi
Member
Registered: 2006-04-30
Posts: 109

Re: A script for setting a random wallpaper

i just found, that you guys massively over-complicate things for no obvious reason. i just put this into a shell script i call from .xinitrc and that's that.

#!/bin/bash
while [ "$DISPLAY" == ":0.0" ]
do
    fbsetbg -R ~/.wallpapers
    sleep 30m
done

Last edited by eNTi (2010-11-02 20:41:25)

Offline

#21 2010-11-02 20:39:02

72linus
Member
From: gordonsville,va
Registered: 2009-03-14
Posts: 144
Website

Re: A script for setting a random wallpaper

awesome!
yes, very simple and quite elegant
great work eNTi!
Thanks

Offline

#22 2010-11-06 14:59:10

JohannesSM64
Member
From: Norway
Registered: 2009-10-11
Posts: 623
Website

Re: A script for setting a random wallpaper

I use this in .xinitrc (an external file is unecessary), which works with any bg setter (as long as it accepts a file as argument):

while :; do
    display -window root "$(find ~/pictures/wps -type f | shuf -n1)"
    sleep 15m
done &

Last edited by JohannesSM64 (2010-11-06 15:01:33)

Offline

Board footer

Powered by FluxBB