首页 > 解决方案 > 如何结束生成的 shell 脚本?

问题描述

我正在编写我的第一个 gnome shell 扩展,通过制作和运行 shell 脚本将桌面背景更新为 Microsoft Daily Wallpaper 这是 shell 脚本,它每 15 分钟循环一次

while :
do
result=$(curl -s -X GET --header "Accept: */*" "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US")
regex="th.+\.jpg"
if [[ $result =~ $regex ]]
then
    gsettings set org.gnome.desktop.background picture-uri "http://bing.com/${BASH_REMATCH[0]}"
fi
sleep 900
done

这是extension.js文件,我做了上面的shell脚本,然后运行它

const Util = imports.misc.util;

const loc = "~/.local/share/gnome-shell/extensions/bingwall@anb1142.io/bing_wallpaper.sh";
function init() {
    const command = `printf 'while :\ndo\nresult=$(curl -s -X GET --header "Accept: */*" "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US")\nregex="th.+\.jpg"\nif [[ $result =~ $regex ]]\nthen\n    gsettings set org.gnome.desktop.background picture-uri "http://bing.com/\${BASH_REMATCH[0]}"\nfi\nsleep 900\ndone\n' > ${loc}`;
    Util.spawn(["/bin/bash", "-c", command]);
    Util.spawn(["/bin/bash", "-c", `chmod +rwx ${loc}`]);
}
function enable() {
    Util.spawn(["/bin/bash", "-c", loc]);
}

function disable() {
    // stop that script
}

这里有问题。我知道如何启动它,但我不知道如何打破该循环或终止脚本。我希望在禁用时发生这种情况。我怎么做 ?提前致谢

标签: gnome-shellgnome-shell-extensions

解决方案


首先,值得指出的是,您不应该在 shell 脚本中执行任何这些操作。libsoupGSettings的组合将允许您在不阻塞 GNOME Shell 的主线程或生成 shell 脚本的情况下做您想做的事情。

gjs.guide上有一个教程,它描述了如何在 GJS中生成和控制子进程。基本上,可以通过调用返回的对象来生成Gio.Subprocess.new()和停止进程:force_exit()

const {Gio} = import.gi;

try {
    // If no error is thrown, the process started successfully and
    // is now running in the background
    let proc = Gio.Subprocess.new(['ls'], Gio.SubprocessFlags.NONE);

    // At any time call force_exit() to stop the process
    proc.force_exit();
} catch (e) {
    logError(e, 'Error executing process');
}

推荐阅读