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`
if [ "$ii" -ne "$$" ] ; then
echo "Killing PID:" $ii
kill -9 $ii

No comments:

Print chess board in command line

The following bash one-liner will print a chess board in a terminal (the script works for the shells bash and ksh only) for (( i = 1; i ...