Update.
[scripts.git] / kill-unused-xterms.sh
1 #!/bin/bash
2
3 #########################################################################
4 # This program is free software: you can redistribute it and/or modify  #
5 # it under the terms of the version 3 of the GNU General Public License #
6 # as published by the Free Software Foundation.                         #
7 #                                                                       #
8 # This program is distributed in the hope that it will be useful, but   #
9 # WITHOUT ANY WARRANTY; without even the implied warranty of            #
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      #
11 # General Public License for more details.                              #
12 #                                                                       #
13 # You should have received a copy of the GNU General Public License     #
14 # along with this program. If not, see <http://www.gnu.org/licenses/>.  #
15 #                                                                       #
16 # Written by and Copyright (C) Francois Fleuret                         #
17 # Contact <francois@fleuret.org> for comments & bug reports             #
18 #########################################################################
19
20 # Kills all xterms which are running bash with no sub-process
21
22 set -e
23
24 NB_KILLED=0
25 NB_TOTAL=0
26 SHELL_NAME=$(basename ${SHELL})
27
28 # Loop through the pid of xterms
29 for ppid in $(ps h -C xterm -o pid); do
30
31     N=0
32
33     # For each, loop through the child shells
34     for pid in $(ps h --ppid $ppid -o pid,cmd | awk '{ if($2 == "'${SHELL_NAME}'") { print $1 }}'); do
35         # For each, count how many sub-process we do have
36         K=$(ps h --ppid $pid -o pid | wc -l)
37         N=$((N+K+1))
38     done
39
40     # If there is only one, kill the xterm
41     if [[ $N == 1 ]]; then
42         kill -USR2 $ppid
43         NB_KILLED=$((NB_KILLED+1))
44     fi
45     NB_TOTAL=$((NB_TOTAL+1))
46 done
47
48 echo "Killed ${NB_KILLED} / ${NB_TOTAL} XTerm(s)"