linux 简单服务启动、关闭脚本
假如我们的目录结构如下:
/home/project/bin/shell # 脚本所在目录
/home/project/TestServer/bin # 可执行程序目录
/home/project/TestServer/lib # 依赖库目录
服务名为:TestServer
启动脚本start.sh:
#!/bin/bash
appName=TestServer
process=`ps -ef | grep ${appName} | grep -v grep | awk '{print $2}'`;
if [ "$process" == "" ]; then
thisDir="$(cd `dirname "$0"` && pwd )"
runDir="${thisDir}/../${appName}/bin"
libDir="${thisDir}/../${appName}/lib"
cd $runDir
export LD_LIBRARY_PATH=$libDir
nohup "$runDir"/$appName &
process=`ps -ef | grep ${appName} | grep -v grep | awk '{print $2}'`;
sleep 1s
echo "------------${appName} start success, pid is ${process}------------"
else
echo "------------${appName} is always running, pid is ${process}------------"
fi
关闭脚本stop.sh
#!/bin/bash
ps -ef | grep TestServer | grep -v grep | awk '{print $2}' | xargs kill -9
echo "------------TestServer is stopped successfully.-------------"
简单解释下:
如果进程已经在运行就直接返回。
process=`ps -ef | grep ${appName} | grep -v grep | awk '{print $2}'`;
获取appName的进程ID,这个语句会过滤掉grep本身,进程ID在第2列。
thisDir="$(cd `dirname "$0"` && pwd )"
获取当前脚本所在目录,赋值给变量thisDir
export LD_LIBRARY_PATH=$libDir
导入程序运行依赖库
nohup "$runDir"/$appName &
不挂断在后台运行