每次关闭 Firefox 窗口时如何执行终端命令

Dus*_*vic 8 command-line firefox bash

我需要执行这个:

rm -rf ~/.wine-pipelight/*;
rm -rf ~/.wine-pipelight/./.*;
cp -a ~/viewright_backup/. ~/.wine-pipelight
Run Code Online (Sandbox Code Playgroud)

每次 Firefox 窗口关闭时。但不一定在所有窗户都关闭时,而是在每个关闭的窗户上。例如,如果我有一个 Firefox 窗口和一个 Firefox 弹出窗口。如果我至少关闭一个窗口,我想执行这个命令。这可能吗?谢谢!

ter*_*don 11

我唯一能想到的方法不是很优雅。您可以在后台运行一个脚本,该脚本计算每秒打开的 Firefox 窗口的数量,并在该数量发生变化时启动您的命令。就像是:

#!/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
Run Code Online (Sandbox Code Playgroud)

将上面的脚本另存为firefox,将其放在您的~/bin目录中并使其可执行chmod a+x ~/bin/firefox。由于 Ubuntu默认添加~/bin到您$PATH的目录并将其添加到任何其他目录之前,因此运行firefox将启动该脚本而不是普通的 firefox 可执行文件。现在,因为脚本正在启动/usr/bin/firefox,这意味着您的普通 Firefox 将出现,正如您预期的那样,只有脚本也在运行。只要您关闭 Firefox,脚本就会退出。

免责声明:

这个脚本是

  1. 不优雅,需要在后台无限循环运行。
  2. 需要xdotool,安装它sudo apt-get install xdotool
  3. 不适用于选项卡,仅适用于窗口。