0

I need to kill a process using the same command in both sh and bash (In a script). Normally I would do the following in bash:

SCRIPT=$(basename $0) #So the script knows itself
killall -9 $SCRIPT #Kill itself

However this does not seem to work using SH

Any suggestions on a solution that will work in either.

Is there an easier or more correct way to completely exit a script. Seems I have revisited this question many times over the years and never found the official correct way.

Atomiklan
  • 5,164
  • 11
  • 40
  • 62
  • What process are you tying to kill? The current shell? – konsolebox Jul 25 '14 at 04:28
  • That should work in both `sh` and `bash`. If you are trying it on different machines, the problem is likely that `killall` (an external command, not part of either `sh` or `bash`) is not available. In any case, don't use `-9` to kill your program; that is intended only for stopping buggy programs that don't respond to any other signal. The default signal (`TERM`) should work fine; failing that, try `INT` (-2). – chepner Jul 25 '14 at 04:28
  • 1
    Why not just use `exit`, though, to end the script? Script suicide seems a little odd. – chepner Jul 25 '14 at 04:30
  • exit didnt seem to work on occasion – Atomiklan Jul 25 '14 at 04:31
  • Ah I bet I know why. exit cant be used inside functions i believe because it just exits the function and doesnt kill the original script. – Atomiklan Jul 25 '14 at 04:35
  • @Atomiklan If you're planning to kill the parent script you can play around with `$PPID` (may only be available to bash). Just make sure you know what you're doing. – konsolebox Jul 25 '14 at 04:36
  • Thanks, I think exit is actually going to work – Atomiklan Jul 25 '14 at 04:40

1 Answers1

1

Basically to let the script kill itself, point it to $$ which presents the process ID of the shell.

kill "$$"

Avoid SIGKILL (9) when not necessary. Only use it on applications that get significantly unresponsive.

The default signal sent is SIGTERM (15), and there are other signals that could also terminate the process which may be safer than SIGKILL. One of those are SIGQUIT, SIGABRT, and SIGHUP.

konsolebox
  • 72,135
  • 12
  • 99
  • 105