如何使用 Cron 在 Linux 中更改桌面背景

Ver*_*ika 1 linux terminal cron wallpaper command-line-interface

我找到了改变桌面壁纸的终端命令:

gsettings set org.gnome.desktop.background picture-uri file:///path/to/your/image.png
Run Code Online (Sandbox Code Playgroud)

但是此命令在 cron 和其他桌面(如 Mate)中不起作用。pgrep gnome-session方法对我来说没有任何意义。

Vas*_*riy 5

您可以使用dconf更改背景。这是简单的 bash 脚本示例:

#!/bin/bash

WP="$(find ~+ -type f -exec mimetype {} + 2>/dev/null | awk -F': +' '{ if ($2 ~ /^image\//) print $1 }' | sort -R | tail -30 | shuf -n 1)"

dconf write /org/mate/desktop/background/picture-filename "'${WP}'"
Run Code Online (Sandbox Code Playgroud)

您可以使用 GUI 应用程序找到特定于发行版的密钥 - dconf-editor

但是要在 CRON 中使用此脚本,您需要设置会话环境变量。命令pgrep gnome-session在 Mint 和其他非 Gnome 桌面中不起作用。要解决此问题,您需要在系统启动时通过运行命令来保存特定用户的环境变量:

env > ~/cronenv && sed -i '/%s/d' ~/cronenv
Run Code Online (Sandbox Code Playgroud)

现在您cronenv在用户主目录中有文件(没有替代变量 - %s)。只需在运行之前将它们恢复到 cron 中dconf

*/1 7-21 * * * cd ~/Pictures && env $(cat ~/cronenv | xargs) /path/to/first/script
Run Code Online (Sandbox Code Playgroud)

使用 crontab -e 编辑当前用户的 cron 作业。一切正常!