2

I've couple instances of script.sh running in parallel, doing the same thing, running in background.

I'm trying to use a function to kill all the current running scripts when executed.

So, for example, ./script.sh -start will start the script (which I can run few in parallel) and when I execute ./script.sh -kill will kill all instances of the script.

f() {
    procName=`basename $0`
    pidsToKill=`ps -ef | grep $procName | grep -v grep | awk '{ print $2 }'`
    if [[ $pidsToKill ]]; then
        for i in $pidsToKill; do
            kill -9 $i
        done
        echo "Killed running scripts."
    else
        echo "No opened scripts to kill"
    fi
}

For some reason, sometimes it kill couple of the scripts and sometimes returns an error.

I've figured a way to solve this, but I want to understand why this one doesn't work. Any ideas?

4
  • 2
    You really shouldn't do that.
    – l0b0
    Aug 19, 2014 at 14:19
  • Why? I know it might not be the best solution, but the script is that simple. I don't need subscripts.
    – Chen A.
    Aug 19, 2014 at 14:48
  • It's explained in detail on linked page.
    – l0b0
    Aug 19, 2014 at 14:53
  • This script also kills itself, less myprogramname/README, and other unrelated processes. Don't do this. Aug 19, 2014 at 22:53

1 Answer 1

3

The script may be killing itself. You might try running the for loop inside a separate subshell ( for i in $pidsToKill; do kill -9 $i; done; echo All dead. ) & and then exit your script.

1
  • Ok gotcha. That make sense. Thank you, and thanks l0b0 too. Putting the command inside ( ), causing it to run in a subshell?
    – Chen A.
    Aug 21, 2014 at 15:46

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.