Search code examples
shellawkprocesskill-process

Killing previous instances at first time,if running


Following is my script 'Infinite.sh' code, I am running this script in background,Before running this script, i want to kill all previous instances. But this is killing my curent instance also.

kill -9 `ps ux|grep Infinite.sh|awk -F\  '{print $2}'`
while true;
do
echo -n "SLEEPING FOR 5 SECOND"
date
sleep 5
done

Solution

  • Just eliminate the current process' PID from the list. To do this making just the minimal change to your code:

    kill -9 `ps ux | grep Infinite.sh | awk -F\  -v pid=$$ 'pid != $2 {print $2}'`
    

    The option -v pid=$$ sets the awk variable pid to the value of the current process' process ID. The expression pid != $2 {print $2} will print a process ID only if it differs from the current process' process ID.

    Simpler Code

    To simplify the code, we could use pgrep:

    kill -9 $(pgrep Infinite.sh | grep -v $$)
    

    Which Signal to Send to Terminate a Process

    As triplee points out in the comments, kill -9 should only be used as a last resort. -9 (SIGKILL) prevents a process from cleaning up after itself, deleting temporary files, etc. Other signals that one may want to try first include -2 (SIGINT), -6 (SIGABRT), or -15 (SIGTERM, which is the default). As for which signals to use, Randal L. Schwartz recommends:

    Generally, send 15, and wait a second or two, and if that doesn't work, send 2, and if that doesn't work, send 1. If that doesn't, REMOVE THE BINARY because the program is badly behaved!

    For more details on why kill -9 should be avoided, see here. For more information on the various Unix signals and their meaning, see wikipedia

    Still Simpler Code

    As mattalxndr points out, modern Linux systems offer pkill which reduces the command needed to:

    pkill Infinite.sh
    

    Unless another signal is specified, pkill sends SIGTERM (15) which is the preferred signal to send for a first attempt to kill a process. pkill offers a variety of options. See man pkill for details.