Reference: https: //blog.csdn.net/hanjiezz/article/details/79571703
To prevent the shell script to perform the same script at the same time need to set the mutex
Simple method, script execution to start generating a lock file, if the lock file exists on behalf of someone executed, the script exits
test.sh
#!/bin/bash LOCKFILE="/tmp/test_lock" if [ -f ${LOCKFILE} ] then echo "someon do the same thing" exit else touch ${LOCKFILE} fi sleep 90 if [ -f ${LOCKFILE} ] then rm -rf ${LOCKFILE} fi
sleep simulation script to perform other operations
Open a terminal execute the script, then the script is not finished at the time of the execution will open another terminal prompt, and then exit
If an accident or force quit the script does not execute the last step to remove lock file during execution, following a script written to avoid this problem
#!/bin/bash if [ -f /var/run/${BASH_SOURCE[0]}.pid ] then ps -ef|grep -v grep|grep ${BASH_SOURCE[0]}|grep `cat /var/run/${BASH_SOURCE[0]}.pid` >> /dev/null if [ $? -eq 0 ];then echo "someone do the same thing" exit 1 fi fi echo $$ > /var/run/${BASH_SOURCE[0]}.pid sleep 90
PS: $ {BASH_SOURCE [0]} is to get the current script name
Judging process for the
1, to determine whether there is a script pid
2, if the script pid, check currently running the script, if you are running and the pid pid file is run on behalf of someone else is in the running to change the script exits
3. If you do not run a pid pid file script represents no one to run the script, put the pid pid file is written to run
PS: script error
test.sh: 2: test.sh: Bad substitution
Need to run with bash