Skip to content
Advertisement

How to close all open terminal windows except the one running a shell script

I wanted to have a script that is capable of killing console windows, that are either running something or not, but at the same time, keep alive the window that executed this script.

Thanks for your help

Advertisement

Answer

You can find the command name of the parent the script (bash, sh, zsh, etc.) then kill all the processes with that command-name. This way you kill all the bash processes but the one running the script. i.e.

C=$(ps -p $(ps -p $$ -o ppid=) o args=)
P=$(ps -p $$ -o pid=)
for p in $(pgrep $C); do
    if [ $p -ne $P ]; then
        kill $p
    fi
done

This is very not portable. If you also want to close the consoles that are running something it becomes even less portable:

C=$(ps -p $(ps -p $$ -o ppid=) o args=)
P1=$(ps -p $$ -o pid=)
P2=$(ps -p $$ -o ppid=)
echo $(pgrep $C)
for p in $(pgrep $C | tail -n +2); do
    [ $p -ne $P1 ] && [ $p -ne $P2 ] && kill -9 $p
done
  • It will not work if the script is launched by another script or in a bash session within another bash session (e.g. a root session)
  • It will not kill the first bash window if the Desktop Environment was not launched by bash (e.g. if you have the desktop environment set to run at startup), to address this issue, you can remove the | tail -n +2 in the for loop.
  • It will also close the console tabs in addition to the windows.
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement