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 TERMINAL_APP=xterm
25 [[ "${TERMINAL_APP}" ]] || TERMINAL_APP=xterm
26
27 NB_KILLED=0
28 NB_TOTAL=0
29 SHELL_NAME=$(basename ${SHELL})
30
31 # Loop through the pid of xterms
32 for ppid in $(ps h -C "${TERMINAL_APP}" -o pid); do
33
34     N=0
35
36     # For each, loop through the child shells
37     for pid in $(ps h --ppid $ppid -o pid,cmd | awk '{ if($2 == "'${SHELL_NAME}'") { print $1 }}'); do
38         # For each, count how many sub-process we do have
39         K=$(ps h --ppid $pid -o pid | wc -l)
40         N=$((N+K+1))
41     done
42
43     # If there is only one, kill the xterm
44     if [[ $N == 1 ]]; then
45         kill -USR2 $ppid
46         NB_KILLED=$((NB_KILLED+1))
47     fi
48     NB_TOTAL=$((NB_TOTAL+1))
49 done
50
51 echo "Killed ${NB_KILLED} / ${NB_TOTAL} XTerm(s)"