1. 限定脚本的执行用户
#################################################################################
#CHECK TO ENSURE ROOT IS RUNNING THE SCRIPT
#################################################################################
login_id=`id | cut -f2 -d "(" | cut -f1 -d")"`
if [ "$login_id" != "root" ]
then
echo "Only the root user can execute this script"
exit 1
fi
2. 防止脚本并行执行
(1)
#################################################################################
#CHECK TO ENSURE ROOT IS RUNNING THE SCRIPT
#################################################################################
login_id=`id | cut -f2 -d "(" | cut -f1 -d")"`
if [ "$login_id" != "root" ]
then
echo "Only the root user can execute this script"
exit 1
fi
2. 防止脚本并行执行
(1)
My_pid=$$
print $My_pid >> temp.file
read input_pid < temp.file
if [[ "$input_pid" == "$My_pid" ]] then
(allow the script. to continue)
else
(exit the script, My_pid was not 1st)
fi
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.
(2)
If only one instance of a script. should run at a given time, a lock
directory could be used to ensure mutual exclusion:
lockname=/tmp/myscript.lock
if mkdir "$lockname"
then
echo >&2 "aquired lock; continuing"
# Remove lock directory when script. terminates
trap 'rmdir "$lockname"' 0
trap "exit 2" 1 2 3 15
else
echo >&2 "lock already held"
echo >&" "another script. instance running?"
exit 1
fi
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/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/228190/viewspace-612685/