How to close other shells besides the current one?

I need a simple script to close other shells / sessions other than the one I am currently logging into. I am stuck on this line:

ps -o pid,tty,comm | grep sh$

This leads to the selection of current shells.

For instance:

 1346 136,0  sh
 1355 136,1  sh

I can use the command ttyto find out my current shell (pts). Then, I think I need a loop.

It is decided:

ps -o pid,tty,comm | grep sh$ | grep -v $$ | awk '{print $1}' | xargs kill -9
+4
source share
6 answers

, . , ps , , , ps, , script. ... , . , ps (Cygwin) -o, , , .

, :

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;

ps, PID . , ps. , PID , .

kill, , , $pidCol parse.

, grep sh, ( ps ( ), ), awk, PID. , PID PID xargs kill -9.

+1

$$ ps awk:

ps -o pid,tty,comm | awk -v curr=$$ '$3 ~ /sh/ && $1 != curr'

$$ PID .

+1

, PID ( ) :

ps -ft

PID :

kill -TERM <PID1> <PID2> <PID3>

BASH, ,

0

tty "" , , :

current=$(tty | cut -d/ -f3-)

ps -o pid,tty,comm, ... :

ps -o pid,tty,comm | awk -v current="$current" 'NR>1 && $2!=current {print $1}'

kill PID.

0

.

pts=$( tty | sed 's/\/dev\(*\)/\1/' ) 
current=$( ps -C sh  | grep $pts | ps -o pid= | head -n 1 )
total=$(ps -C sh -o pid= )
for i in $total ; do                         
    if [[ $i -ne $current ]] ; then
            kill -9 $i
    fi
done
0
pgrep -u $USER | grep -v "`pgrep -s 0`" | xargs kill

PID . xargs, .

0

All Articles