Shell script to avoid repeated execution

Reference:
Shell script to avoid repeated execution methods
https://m.jb51.net/article/60285.htm
Shell special variables: Shell $ 0, $ #, $ *, $ @, $ ?, $$ and command line parameters
https : //www.cnblogs.com/davygeek/p/5670212.html
Linux shell string operations (length, find, replace) detailed explanation
https://www.cnblogs.com/chengmo/archive/2010/10/02/1841355 .html
shell script-logical judgment and string comparison
https://www.cnblogs.com/-beyond/p/8262265.html


Just add the following code at the beginning of the singleton mode script to avoid repeated execution

# Get the fullname of proces with full path
basePath=$(cd `dirname $0`; pwd)
fullPathProc=$basePath/${0##*/}

# Run the proces by fullname
if [ $fullPathProc != $0 ]; then
  /bin/bash $fullPathProc
  exit 1
fi

# Check if the proces is running
pCount=$(ps -ef | grep $fullPathProc | grep -v 'grep' | grep -v ' -c sh' | grep -v $$ | grep -c 'sh')
if [ $pCount -gt 0 ]; then
  echo "$fullPathProc is running ..." 
  exit 0
fi

echo "$fullPathProc is starting now ..."
sleep 1800


For example, save as t.sh, and then run sh t.sh in two terminals to verify the effect.

Explanation:
$ 0: The name of the current script, not necessarily including the full path
$$: The process ID of the current script is PID, which is also the PPID of its subshell. Filtering it out can exclude this process and subprocesses
grep -v '-c sh': The script run by crontab will have one more process -c sh
grep -c 'sh': count the number of keyword sh, which is count
 

 

Published 27 original articles · praised 4 · visits 9695

Guess you like

Origin blog.csdn.net/yoshubom/article/details/88544909