How to execute a terminal command every time the firefox windows closes

Solution 1:

The only way I can think of is not very elegant. You can have a script running in the background that counts the number of open firefox windows every second and launches your command if that number changes. Something like:

#!/usr/bin/env bash


## Run firefox
/usr/bin/firefox &

## Initialize the variable to 100
last=100;

## Start infinite loop, it will run while there
## is a running firefox instance.
while pgrep firefox >/dev/null;
do
    ## Get the number of firefox windows    
    num=$(xdotool search --name firefox | wc -l)

    ## If this number is less than it was, launch your commands
    if [ "$num" -lt "$last" ]
    then
        rm -rf ~/.wine-pipelight/*;
        ## I included this since you had it in your post but it
        ## does exactly the same as the command above.
        rm -rf ~/.wine-pipelight/./.*;
        cp -a ~/viewright_backup/. ~/.wine-pipelight      
    fi

    ## Save the number of windows as $last for next time
    last=$num

    ## Wait for a second so as not to spam your CPU.
    ## Depending on your use, you might want to make it wait a bit longer,
    ## the longer you wait, the lighter the load on your machine
    sleep 1

done

Save the script above as firefox, put it in your ~/bin directory and make it executable chmod a+x ~/bin/firefox. Since Ubuntu adds ~/bin to your $PATH by default and adds it before any other directories, running firefox will launch that script instead of the normal firefox executable. Now, because the script is launching /usr/bin/firefox, this means that your normal firefox will appear, just as you expect, only with the script running as well. The script will exit as soon as you close firefox.

DISCLAIMER:

This script is

  1. Not elegant, it needs to be run as an infinite loop in the background.
  2. Requires xdotool, install it with sudo apt-get install xdotool
  3. Does not work for tabs, only windows.