#/bin/bash
while true;
do
count=`ps -ef | grep test.jar | grep -v grep|wc -l`
if [ ${count} -lt 1 ]; then
nohup java -jar xxx.jar >log.out 2>&1  &
else
echo "process is running"
fi
sleep 3
done

Linux Shell脚本:自动读取pid并关闭进程

查询进程信息

ps -ef|grep elasticsearch

过滤掉grep进程

ps -ef|grep elasticsearch|grep -v grep

提取pid(awk以空格分割,显示第二个变量即为pid)

ps -ef|grep elasticsearch|grep -v grep|awk '{print $2}'

根据pid kill掉该进程

完整脚本如下所示