Shell脚本更改桌面壁纸

11
可以编写最简单的 shell 脚本来更换 Ubuntu 桌面壁纸,设置为定期更换(例如每分钟更换一次)。
壁纸将保存在特定目录中(例如 $ HOME / wallpapers)。我只需要基本功能。
1)从 $HOME / wallpapers 中选择随机壁纸 2)将其设置为桌面壁纸 3)设置 cron 每分钟运行脚本(不是问题的一部分)。

也许这个问题应该在askubuntu.com上问? - Kaivosukeltaja
9
这里有5259个被标记为bash的问题。但在askubuntu上只有144个。这个问题是关于编程的。Ubuntu更多关注桌面环境。 - xralf
基本上这取决于你的桌面环境 / 窗口管理器。在这个问题中,包括问题提出者在内的每个人似乎都使用 Gnome,因此使用 gnome-tools 的答案有效。对于将来使用 KDE / XFCE / LXDE / MATE / 其他桌面环境的访问者,请询问您的桌面环境如何以编程方式设置其壁纸。 - Nikana Reklawyks
8个回答

14
#!/bin/bash
wallpaperdir='$HOME/wallpaper'

files=($wallpaperdir/*)
randompic=`printf "%s\n" "${files[RANDOM % ${#files[@]}]}"`

gconftool-2 -t str --set /desktop/gnome/background/picture_filename "$randompic"

保存此脚本并使用命令 "crontab -e" 进行编辑(它会启动一个编辑器,在文件末尾添加此行):

*/1     *     *     *     *         /bin/bash /path/to/script.sh

编辑:我假设您正在使用GNOME。如果不是,您需要编辑最后一行,因为我的示例使用了Gnome Conftool。;)

要更改XFCE中的背景,请更改包含gconftool-2的行:

echo -e “# xfce backdrop list\n$randompic”>$HOME/.config/xfce4/desktop/backdrops.list    
killall -USR1 xfdesktop

谢谢。我正在使用 GNOME 和 XFCE。您知道如何在 XFCE 中更改它吗? - xralf
这个不起作用。我可以把文件发给你吗?如果没有错误的话? - xralf
你需要查看 $HOME/.config/xfce4/desktop/backdrops.list,它应该存在,并且在执行最后一个命令后,应该会有一个新条目。但是你可以将文件粘贴到pastebin或类似的地方,我们会解决这个问题;-) - tamasgal
抱歉,我错过了你的评论。这里是 pastebin 链接:http://paste.ubuntu.com/591151/。 - xralf
为什么不直接使用 gconftool-2 -t str --set /desktop/gnome/background/picture_filename "${files[RANDOM % ${#files[@]}]}",摆脱无用的变量 randompic、子shell 和丑陋的语法呢? - gniourf_gniourf
显示剩余3条评论

4

我知道这个回答有点晚了,但由于它可能对一些人有帮助,所以我发布了它。

从septi的代码加上一些修改,这是我的解决方案:

#!/bin/bash
wallpaperdir="$HOME/wallpaper"

files=($wallpaperdir/*)
randompic=`printf "%s\n" "${files[RANDOM % ${#files[@]}]}"`

echo -e "# xfce backdrop list\n$randompic">$HOME/.config/xfce4/desktop/backdrop.list
xfdesktop --reload

为了让计算机正确解释$HOME部分,必须用双引号替换单引号。此外,您想要编辑的文件是backdrop.list,而不是backdrops.list。最后,在这种情况下使用killall有点过度,因为您可以简单地重新加载xfdesktop。我已经在我的计算机(Linux Mint Debian Edition)上进行了测试,似乎完美运行。希望它有所帮助。=)
编辑:我忘记提到,在crontab中的命令之前添加DISPLAY=:0.0。
*/1 * * * * DISPLAY=:0.0 wallpaper.sh

3

这只是我的处理方式。我并不声称它是最理想的。

WALLS_PATH=/path/to/images
cd $WALLS_PATH

while [ 1 ]; do
    for NEW_WALL in "$WALLS_PATH"/*; do
        gsettings set org.gnome.desktop.background picture-uri "file://${NEW_WALL}"
        sleep 1800
    done
done

2

对于gnome3,您需要使用gsettings而不是gconftool。

但是,如果您将通过cron执行脚本,它将无法正常工作。

我尝试过很多.sh脚本,但都没有成功。

最后,我使用了这个Python脚本来从文件夹中加载随机壁纸:

#!/usr/bin/env python
#coding: utf8 

import os,random
setup = "/path_to_folder/" + random.choice(os.listdir("/path_to_folder/"))
os.system("DISPLAY=:0 GSETTINGS_BACKEND=dconf gsettings set org.gnome.desktop.background picture-uri  'file://%s'" %(setup))

希望这对于有着和我一样问题的人有所帮助!

2

在较新的Ubuntu中尝试以下命令:gsettings set org.gnome.desktop.background picture-uri file:///path/to/img.jpg(来自这里的提示


1

在Gnome中,这对我有效:

#!/bin/bash

DIR="/home/user/Pictures/wallpapers"
PIC=$(find $DIR -type f -maxdepth 1 | shuf -n1)
gsettings set org.gnome.desktop.background picture-uri "file://$PIC"

一个小提示: 不要依赖/解析 ls 的结果,使用 find 更合适。 - user4113344

1

这并不简单,但对我来说很有效。您还可以在github上找到它:kendalla59/wallup

#!/bin/bash
#
# wallup
#   Update wallpaper images on a timed basis.

# This directory contains images to use as desktop wallpaper.
DEFAULT_WPHOME="$HOME/Pictures/Wallpaper"

# Any files with the following file extensions will be used.
WPEXTS=(jpg png gif jpeg JPG)

# This is the interval between wallpaper image updates, in seconds.
WPTIME=$((10 * 60))

# This is the name of the subdirectory to place the images
# that have been previously selected at random for wallpaper.
WPSAVE=.wpsave

# This variable enables two images to be used side-by-side for
# a dual monitor configuration.
#WPDUAL=false
WPDUAL=true

WPCVTS=0

# Prior to running this script, set the WPHOME environment
# variable to set a non-default wallpaper folder.
if [[ -z "$WPHOME" ]]; then
    if [[ -d "$DEFAULT_WPHOME" ]];  then WPHOME=$DEFAULT_WPHOME
    elif [[ -d "$HOME/Pictures" ]]; then WPHOME=$HOME/Pictures
    else                                 WPHOME=$HOME
    fi
fi

WPDEST="$WPHOME"/"$WPSAVE"
if [[ ! -d "$WPDEST" ]]; then
    mkdir "$WPDEST"
    if [[ $? != 0 ]]; then
        echo "Unable to create $WPDEST. Exiting..."
        exit
    fi
fi

function getdate {
    printf -v WPDATE '%-5d %s %s' $$ $(date +"%D %I:%M%p")
}
getdate

WPHIST="$WPDEST"/wallup.log
WPLOCK="$WPDEST"/.mult-lock
WPLPID="$WPLOCK"/lock-$$

echo "$WPDATE  Starting wallpaper updater for user $USER." >> "$WPHIST"

# Check if we can merge two images for the background.
if $WPDUAL; then
    hash convert >& /dev/null
    if [[ $? -ne 0 ]]; then
        WPDUAL=false
        echo "$WPDATE  Install \"imagemagick\" for dual displays." >> "$WPHIST"
        echo "$WPDATE  ->  (sudo apt install imagemagick)" >> "$WPHIST"
    fi
fi

# If an old lock file exists, clear it out now.
if [[ -d "$WPLOCK" ]]; then
    for oldfile in "$WPLOCK"/*; do
        if [[ -f "$oldfile" ]]; then
            echo "$WPDATE  Removing old lock \"$oldfile\"." >> "$WPHIST"
            rm "$oldfile"
        fi
    done
else
    mkdir "$WPLOCK"
fi

# Create a new lock file for this process ID
touch "$WPLPID"

function getnext {

    # Randomly select the next wallpaper image(s).
    cd "$WPHOME"
    WPNEXT=$(ls ${WPEXTS[@]/#/"*."} 2> /dev/null | shuf -n 1)

    # If no image was found, reload images from the saved folder.
    if [[ "$WPNEXT" == "" ]]; then
        cd "$WPDEST"
        WPFCNT=$(ls -1 ${WPEXTS[@]/#/"*."} 2> /dev/null | wc -l)
        echo "$WPDATE  Moving $WPFCNT image files from $WPSAVE back up to $WPHOME." >> "$WPHIST"
        mv ${WPEXTS[@]/#/"*."} "$WPHOME" 2> /dev/null

        # Now get a random wallpaper image.
        cd "$WPHOME"
        rm cvt-*.png
        WPCVTS=0
        WPNEXT=$(ls ${WPEXTS[@]/#/"*."} 2> /dev/null | shuf -n 1)

        # Quit now if there are no images in the wallpaper folder.
        if [[ "$WPNEXT" == "" ]]; then
            echo "$WPDATE  No Wallpaper images found in $WPHOME. Exiting..." >> "$WPHIST"
            rm -f "$WPLPID"
            exit
        fi
    fi

    # If the destination directory has disappeared, exit now.
    if [[ ! -d "$WPDEST" ]]; then
        echo "No directory $WPDEST. Exiting..."
        exit
    fi
}

while true; do

    # Responsiveness to logout or multiple instances is determined
    # by the WPRESP variable, the time to respond in seconds.
    WPWAIT=$WPTIME
    WPRESP=10

    while [[ $WPWAIT -gt 0 ]]; do
        if [[ ! -f "$WPLPID" ]]; then
            getdate
            echo "$WPDATE  Missing \"$WPLPID\". Exiting..." >> "$WPHIST"
            exit
        fi

        sleep $WPRESP
        WPWAIT=$((WPWAIT - WPRESP))

        if [[ $(ps -C gnome-shell -o euser= | grep $USER) == "" ]]; then
            getdate
            echo "$WPDATE  User $USER not logged in. Exiting..." >> "$WPHIST"
            rm -f "$WPLPID"
            exit
        fi
    done
    getdate

    ((WPCVTS+=1))
    WPFILE="$WPDEST"/cvt-$WPCVTS.png

    getnext
    if $WPDUAL; then
        WPNEXT1=$WPNEXT
        mv "$WPHOME"/"$WPNEXT1" "$WPHOME"/"$WPNEXT1".HOLD
        getnext
        WPNEXT2=$WPNEXT
        mv "$WPHOME"/"$WPNEXT1".HOLD "$WPDEST"/"$WPNEXT1"
        mv "$WPHOME"/"$WPNEXT2" "$WPDEST"

        # Create the merged background image.
        cd "$WPDEST"
        convert "$WPNEXT1" "$WPNEXT2" +append "$WPFILE"
        echo "$WPDATE  New wallpaper file://$WPFILE (from $WPNEXT1 + $WPNEXT2)" >> "$WPHIST"
    else
        mv "$WPHOME"/"$WPNEXT" "$WPDEST"
        WPFILE="$WPDEST"/"$WPNEXT"
        echo "$WPDATE  New wallpaper file://$WPFILE" >> "$WPHIST"
    fi

    gsettings set org.gnome.desktop.background picture-uri file://"$WPFILE"

done

0

很遗憾,单独使用random函数是不够的。

它可能会再次选择相同的文件。这真让人恼火。

你需要像这样的东西

  shuffle(items: string[]) {
    console.log('shuffling...')
    this.items = items.reduce(
      ([original, shuffled]) =>
        [original, [...shuffled, ...original.splice(Math.random() * original.length | 0, 1)]],
      [[...items], []]
    )[1]
    this.cursor = undefined
    return this.items
  }

我刚刚发布了一款免费的随机壁纸应用程序,可以实现这个功能。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接