How to close other shells except current?
This is actually not as easy as it might seem at first. The main challenge is that the ps
utility is rather incompatible between different platforms, which creates a very significant risk that assumptions you make about ps
won't always be correct on systems where you might use the script. And since the task is a rather... dangerous one, you would want to be careful here. Just as an example, the ps
on my current system (Cygwin) does not have a -o
option, while yours appears to have one.
Anyway, here's my solution:
pidCol=$(ps| head -1| awk '{ for (i = 1; i <= NF; ++i) if ($i == "PID") { print(i); exit; }; };');if [[ -n "$pidCol" ]]; then ps| tail -n+2| grep sh$| cut -c2-| awk "{ print(\$$pidCol); };"| grep -v "^$$\$"| xargs kill -9;fi;
It first gets the column number in ps
's output that contains the PID of the process. I tried to make it as robust as possible by parsing the ps
header line. So if the PID column position varies between systems, we should still get it correctly for the current system.
Then, I've applied a guard around the kill pipeline to ensure it only runs if we successfully got the $pidCol
from the parse command.
Then, in the actual kill pipeline, I strip off the header, grep for all sh
processes, cut off the first character (because ps
on some systems prints a little character indicator at the beginning of some (but not all) lines that does not get a corresponding column name in the header line), and then use awk
to just print the PID column value. Finally, I grep out the current process's PID and run the remaining PIDs through xargs kill -9
.
You can get your current shell with tty
and "clean" it to get the data after the 2nd slash like this:
current=$(tty | cut -d/ -f3-)
Then, it is a matter of printing all the results in ps -o pid,tty,comm
whose second column does not match your current one... and leaving the header out:
ps -o pid,tty,comm | awk -v current="$current" 'NR>1 && $2!=current {print $1}'
Then, you can loop through this result and kill
the given PIDs.