SHELL编程中常用的一些方法

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值