gnome-shellgnome-shell-extensions

How do I end spawned shell script in?


I am writing my first gnome shell extension to update desktop background to Microsoft Daily Wallpaper by making and running a shell script Here's the shell script, it loops every 15 minutes

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

Here is the extension.js file, I made it to make the the shell script above, then run it

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
}

Here's problem. I know how to start it but I don't know how to break that loop or kill the script. I want that to happen when disabling. How do I do that ? Thanks in advance


Solution

  • First, it's worth pointing out that you shouldn't be doing any of this in a shell script. A combination of libsoup and GSettings will allow you to do what you want without blocking GNOME Shell's main thread, or spawning a shell script.

    There is a tutorial on gjs.guide which describes how to spawn and control Subprocesses in GJS. Basically, processes can be spawned with Gio.Subprocess.new() and stopped by calling force_exit() on the returned object:

    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');
    }