1833128 Members
4018 Online
110051 Solutions
New Discussion

Shell program query

 
Vasudevan MV
Frequent Advisor

Shell program query

Hi,

Can any one tell me how to kill the same shell?. I have written a script, it looks like this

pids=`ps |grep sh | awk '{print $1}'
echo $pids
......
kill -9 $pids

I ran this script in two ways on the prompt:
1. $exam_script (failed to kill itself)
2. $. exam_script (killed itself)
But in the first condition its giving a message like "Killed". My question is why it is not able to kill the parent shell from the child shell?.

Thanks
Vasu
4 REPLIES 4
Peter Kloetgen
Esteemed Contributor

Re: Shell program query

Hi,

try simply the command:

kill -9 $$

$$ will be replaced by the PID of your shell.


Allways stay on the bright side of life!

Peter
I'm learning here as well as helping
Bill Hassell
Honored Contributor

Re: Shell program query

Very important: ps and grep will *ALWAYS* give you unwanted entries!!! Try to avoid using grep with ps. In your case, ps|grep sh will give you ksh bash and lots of other unrelated processes like users that have sh in their user name.

Instead, use the -C option in ps. NOTE: this an XPG4 option, so temporarily set UNIX95 so it will work. For your example:

pids=$(UNIX95= ps -C sh)

To find all sh shells:

pids=$(UNIX95= ps -efC sh)


Bill Hassell, sysadmin
Vasudevan MV
Frequent Advisor

Re: Shell program query

Peter,

I have tried this also already, but I got the same message like "killed" but failed to parent shell.

Bill,
As you mentioned the option in your reply, it gives all the shell pids, but How do I kill a parent shell from a child shell?

Thanks
Vasu
Steven Sim Kok Leong
Honored Contributor

Re: Shell program query

Hi,

To kill the parent shell of your script within your script, instead of $$, use $PPID.

kill -9 $PPID

This works because while $$ is the PID of your current shell (i.e. killing this PID kills your script), $PPID is the PID of your parent shell (i.e. killing this PID kills the shell from which your script is launched).

Hope this helps. Regards.

Steven Sim Kok Leong