@xtccc
2016-07-01T16:14:49.000000Z
字数 1351
阅读 3691
Shell
目录
#!/bin/bash# 不论从哪里执行start.sh, 都会进入start.sh的所在目录SOURCE="${BASH_SOURCE[0]}"BIN_DIR="$( dirname "$SOURCE" )"cd $BIN_DIRPidFile=".pid"LogDir="logs"if [ -f $PidFile ]; then # .pid文件是否存在pid=`tail -1 $PidFile` # .pid文件最后一行的内容if [ "x" != "x$pid" ]; then # 变量pid是否有值ret=`ps aux | awk '{print $2}' | grep $pid`if [ "x" != "x$ret" ]; thenecho "发现正在运行的DataService(pid = $pid), 请勿再次启动"exit $?fififiif [ ! -d $LogDir ]; thenmkdir $LogDirfi# 后台运行命令,并将日志重定向nohup $cmd >"$LogDir/nohup.out" 2>&1 &pid=$! # $!是最近被执行的后台进程的pidecho "DataService开始运行, pid = $pid"echo "$pid" >> "$PidFile" # 将pid写入到.pid文件
注意点
在判断一个变量是否有值的时候,我们使用了:
if [ "x" != "x$pid" ] ...
我们没有用下面的方式,因为发现它不靠谱:
if [ ! -z x ] ...
#!/bin/bashPidFile=".pid"if [ ! -f $PidFile ]; thenecho "当前未运行 (没有找到pid文件)"exit $?fipid=`tail -1 $PidFile`if [ "x" == "x$pid" ]; thenecho "当前未运行 (存在pid文件, 但是其中没有任何pid)"exit $?firet=`ps aux | awk '{print $2}' | grep $pid`if [ "x" == "x$ret" ]; thenecho "当前未运行 (目标pid = $pid)"exit $?fiecho "正在停止DataService (目标pid=$pid)"kill -9 $pidecho "DataService已停止"
注意点
我们使用了 $? 来输出返回值,参考 returning value from called function in shell script
#!/bin/bashPidFile=".pid"if [ ! -f $PidFile ]; thenecho "未运行 (原因: 没有找到pid文件)"exit $?fipid=`tail -1 $PidFile`if [ "x" == "x$pid" ]; thenecho "未运行 (原因: 存在pid文件, 但是其中没有任何pid)"exit $?firet=`ps aux | awk '{print $2}' | grep $pid`if [ "x" == "x$ret" ]; thenecho "未运行"exit $?elseecho "正在运行 (pid=$pid)"exit $?fi
