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 cur
Anything can be dangerous. The better solution is to save your PID to a file everytime you run an instance. If a PID file exists and if the PID in that file is a valid and is an active process, kill that process. Save the PID of the current process after.
PID_FILE=/var/run/infinite.pid
# Read saved PID of previous instance.
read PID < "$PID_FILE"
# You may consider other safer signals like TERM, HUP, QUIT, and ABRT.
# Checking may also be optional. You can just send the signal right away.
kill -s 0 "$PID" &>/dev/null && kill -s 9 "$PID" &>/dev/null
# Optionally wait for process to exit.
sleep 2s
# Optionally check it again.
kill -s 0 "$PID" &>/dev/null && { echo "Unable to kill process $PID."; exit; }
# Save PID.
echo "$$" > "$PID_FILE"