1

I'm trying a simple test to kill a script from within its self. It doesn't seem to be working.

function testKill
{
  PID=$$
  kill $PID
  echo  hello!
}

When I run this function,

[....]$ testKill
hello!

It clearly doesn't kill the process. How do I make the process terminate before sending the echo command?

When I move this all into an external script, it terminates correctly if I call the script directly from the command line. However, if I make a function inside my .bash_profile and call the script from within that function, the script isn't killed and it prints instead. How do I integrate it into my .bash_profile?

This is a minimal working example to use in a more complicated script.

  • 1
    what if you add a sleep 1 to give the signal handler chance to receive the signal before running the echo ? – steve Jul 3 '17 at 21:26
  • 2
    First you script works just fine! 2. Why bother declaring PID and not just kill $$, this works and is A WHOLE LINE shorter! – ADDB Jul 3 '17 at 21:27
  • @steve I should get delivered before kill returns, provided kill is a builtin (as it usually is). – PSkocik Jul 6 '17 at 19:07
6

You haven't written a script in your example; it's a function. You're therefore applying the kill to your interactive shell session. Interactive shells ignore most signals, including the SIGTERM that you're sending.

Put the function and its call in a script and run that. It's far more likely to do what you expect.

  • I've moved this into an external script, and it terminates correctly if I call the script directly from the command line. However, if I make a function inside my .bash_profile and call the script from within that function, the script isn't killed and it prints instead. How do I integrate it into my .bash_profile? – avikarto Jul 6 '17 at 14:35
  • @avikarto you asked how to kill a script from itself. The answer is kill $$, but it does not work on interactive shells. An interactive shell is not a script. – roaima Jul 6 '17 at 16:19
0

try following, if you want to use it as function directly in bash, respectively sourced from console.

function testKill
{
  kill $PPID
  echo  "no hello :-/"
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.