Search code examples
bashimagemagickzshwallpaper

Shell script for wallpaper with average for background color


Awhile ago I wrote a script for automatically changing wallpapers for my multimonitor setup. I wanted to change it so that the color that fills the extra space is an average of the images, but it just seems to kill the script when I try. Here's what I've got:

#!/bin/sh

BACKGROUND="-background #452036"
GRAVITY="-gravity Center"
GRAVITY2="-gravity North"
GRAVITY3="-gravity South"
LEFT_SIZE=1920x1062
RIGHT_SIZE=1280x958
FINAL_SIZE=3200x1080

RANDOM=$$$(date +%s)
FILES=($1/*)
NUM_FILES=${#FILES[*]}
LEFT_IMAGE=${FILES[$RANDOM % $NUM_FILES]}
RIGHT_IMAGE=${FILES[$RANDOM % $NUM_FILES]}

LCOLOR=${convert $LEFT_IMAGE -resize 1x1\! -depth 8 txt:- | tail -1 | grep -E -o "#(.)* " | cut -f1 -d" "}
RCOLOR=${convert $RIGHT_IMAGE -resize 1x1\! -depth 8 txt:- | tail -1 | grep -E -o "#(.)* " | cut -f1 -d" "}
LBACKGROUND="-background" $LCOLOR
RBACKGROUND="-background" $RCOLOR


convert $LBACKGROUND $GRAVITY -scale $LEFT_SIZE ${LEFT_IMAGE}\
    -extent $LEFT_SIZE ~/.left.png

convert $RBACKGROUND $GRAVITY -scale $RIGHT_SIZE ${RIGHT_IMAGE}\
    -extent $RIGHT_SIZE ~/.right.png

convert $BACKGROUND $GRAVITY2 +append \
~/.left.png \
~/.right.png \
~/.wpcompo.png

convert $BACKGROUND $GRAVITY3 -extent $FINAL_SIZE ~/.wpcompo.png ~/.wallpaper.png

It returns:

/home/ryan/Scripts/wpconvert.sh: line 17: ${convert ${LEFT_IMAGE} -resize 1x1\! -depth 8 txt:- | tail -1 | grep -E -o "#(.)* " | cut -f1 -d" "}: bad substitution

Solution

  • I assume you want to run convert in a subshell, so you need $() instead of ${}:

    LCOLOR=$(convert $LEFT_IMAGE -resize 1x1\! -depth 8 txt:- | tail -1 | grep -E -o "#(.)* " | cut -f1 -d" ")
    RCOLOR=$(convert $RIGHT_IMAGE -resize 1x1\! -depth 8 txt:- | tail -1 | grep -E -o "#(.)* " | cut -f1 -d" ")