我写了一个更改墙纸的 bash 脚本(适用于 GNOME3)。
#!/bin/bash
# Wallpaper's directory.
dir="${HOME}/images/wallpapers/"
# Random wallpaper.
wallpaper=`find "${dir}" -type f | shuf -n1`
# Change wallpaper.
# http://bit.ly/HYEU9H
gsettings set org.gnome.desktop.background picture-options "spanned"
gsettings set org.gnome.desktop.background picture-uri "file://${wallpaper}"
在终端仿真器(例如 gnome-terminal)中执行的脚本效果很好。在 cron 或 ttyX 终端执行期间出现错误:
** (process:26717): WARNING **: Command line `dbus-launch --autolaunch=d64a757758b286540cc0858400000603 --binary-syntax --close-stderr' exited with non-zero exit status 1: Autolaunch error: X11 initialization failed.\n
** (process:26717): WARNING **: Command line `dbus-launch --autolaunch=d64a757758b286540cc0858400000603 --binary-syntax --close-stderr' exited with non-zero exit status 1: Autolaunch error: X11 initialization failed.\n
** (process:26721): WARNING **: Command line `dbus-launch --autolaunch=d64a757758b286540cc0858400000603 --binary-syntax --close-stderr' exited with non-zero exit status 1: Autolaunch error: X11 initialization failed.\n
** (process:26721): WARNING **: Command line `dbus-launch --autolaunch=d64a757758b286540cc0858400000603 --binary-syntax --close-stderr' exited with non-zero exit status 1: Autolaunch error: X11 initialization failed.\n
最佳答案
经过多次尝试,我终于设法解决了这个问题。
确实,问题的发生是因为 cron 只使用了一组非常有限的环境变量。当这被设置为 cron 作业时,唯一负责以正确方式运行问题脚本的环境变量是 DBUS_SESSION_BUS_ADDRESS
,而不是 DISPLAY
或 XAUTHORITY
或 GSETTINGS_BACKEND
或其他。 this answer 中也很好地指出了这一事实.
但问题在this answer 不能保证 ~/.dbus/session-bus/
目录中的文件中的 DBUS_SESSION_BUS_ADDRESS
变量已更新为当前值来自当前的 gnome session 。要解决这个问题,一种方法是在当前 gnome session 中找到进程的 PID,并从其环境中获取 dbus 地址。我们可以这样做:
PID=$(pgrep gnome-session) # instead of 'gnome-session' it can be also used 'noutilus' or 'compiz' or the name of a process of a graphical program about that you are sure that is running after you log in the X session
export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$PID/environ|cut -d= -f2-)
话虽这么说,脚本应该是这样的:
#!/bin/bash
# TODO: At night only dark wallpapers.
# Wallpaper's directory.
dir="${HOME}/images/wallpapers/"
# export DBUS_SESSION_BUS_ADDRESS environment variable
PID=$(pgrep gnome-session)
export DBUS_SESSION_BUS_ADDRESS=$(grep -z DBUS_SESSION_BUS_ADDRESS /proc/$PID/environ|cut -d= -f2-)
# Random wallpaper.
wallpaper=`find "${dir}" -type f | shuf -n1`
# Change wallpaper.
# http://bit.ly/HYEU9H
gsettings set org.gnome.desktop.background picture-options "spanned"
gsettings set org.gnome.desktop.background picture-uri "file://${wallpaper}"
关于linux - 带 cron 的 Gsettings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10374520/