print $My_pid >> temp.file
read input_pid < temp.file
if [[ "$input_pid" == "$My_pid" ]] then
(allow the script. to continue)
(exit the script, My_pid was not 1st)
This guarantees that the first instance of the script. submitted will run
and any other occurances of the same script. will exit. Remove temp.file
before the script. ends and I suggest using a Trap. Better than trying to
deal with ps/grep and it make a nice little function.
If only one instance of a script. should run at a given time, a lock
directory could be used to ensure mutual exclusion:
if mkdir "$lockname"
echo >&2 "aquired lock; continuing"
# Remove lock directory when script. terminates
trap 'rmdir "$lockname"' 0
trap "exit 2" 1 2 3 15
echo >&2 "lock already held"
echo >&" "another script. instance running?"
This can be extended to e.g. write the current process id to a file in the
lock directory. This way another instance can check if the process that
aquired the lock is still running.
来自 “ ITPUB博客 ” ，链接：http://blog.itpub.net/228190/viewspace-612685/，如需转载，请注明出处，否则将追究法律责任。