A bash script snippet to find if another instance of the same script is running in background. This code snippet is very useful for those scripts which have to stay in the background and do some scheduled tasks or just plain monitoring like the laptop battery. It is supposed to be included at the beginning of the code. It would check if another instance of the script is running as a background job. If yes then it issues a warning and terminates the script.
A note of warning : For multicore CPUs it is a tricky deal to figure the actual number of instances. If CPU is dualcore then echo ${run_count} outputs 2 for the first run. And for the second time around it outputs 3. The extra number is the suspended instance of the script. For quadcore the number would go as 4 -> 5 -> 6. For for the first time just run without the comment on echo ${run_count} and then set the value of exp_count (2 for dualcore , 4 for quadcore etc.).
================================================
process=$0
# value of this exp_count depends on the number of cores of CPU. check the process on first run and apply the value here. Need to uncomment the line #echo ${run_count} to chcck no. of cores used by kernel. It maybe different for the physical no. of cores.
exp_count=2
run_count=`ps aux | grep $process | grep -v 'grep' | wc -l`
# uncomment this line to chcck no. of cores used by kernel. It maybe different for the physical no. of cores.
#echo ${run_count}
if [ ${exp_count} -eq ${run_count} ] ; then
echo
else
echo "another instance is running"
exit
fi
Comments