Sunday, January 29, 2012

Self terminating code for bash scripts

Self terminating code for bash scripts is very easy. But have to be sure not to kill itself in the process. The procedure is simple. Find all the PID with the same name as itsself $0 and then kill all those instances one by one in a for loop except itself $$ (PID of its own).

This is a very general script and could be used anywhere and in any script.


===================================
if [ "$1" != "" ] ; then
# if no command line parameter supplied then move on.
if [ "$1" == "kill" ] ; then
# if command line parameter is "kill" then kill all running instances of this script.
nnn=`ps aux | grep $0 | tr -s " " | cut -d" " -f2 `
echo -e $$ "\n====" # prints PID of this instance of script. make sure not to kill itself.
for ii in `echo $nnn`
do
if [ "$ii" -ne "$$" ] ; then
echo "Killing PID:" $ii
kill -9 $ii
fi
done
exit
fi
fi

No comments:

OK GOOGLE on Samsung Galaxy S7 doesn’t work

To make Ok Google detection work on Galaxy S7 (Galaxy series phones) we need to perform a couple of steps. 1. As long as Samsung S vo...