shell脚本判断进程是否存在,杀掉并重启进程

有两种方法

1、方法一

#!/bin/sh
# 统计pid行数
pidCount=`ps -ef|grep manager|grep -v "grep"|wc -l`

#如果行数=1,就杀掉进程
if [ "$pidCount" = "0" ]; then
	echo "进程未运行"

elif [ "$pidCount" = "1" ]; then
	true_pid=`ps -ef|grep manager |grep -v "grep"|awk '{print $2}'`
	echo "pid = $true_pid"
    kill -9 $true_pid
fi
sleep 1

# 启动进程
nohup java -jar  manager*.jar &

2、方法二

#!/bin/sh

# 查找pid
true_pid=`ps -ef | grep manager | grep -v "grep" | awk '{print $2}'`

# 判断pid是否存在,存在就杀掉进程
if [[ ${
    
    true_pid} != "" ]]
then
    echo "pid = $true_pid"
    kill -9 $true_pid
else
    echo "进程未运行"
fi

sleep 1
# 启动进程
nohup java -jar  manager*.jar &

备注:
grep -v 是反向查找的意思,比如 grep -v “grep” 就是查找不含有 grep 字段的行。
wc -l 是统计行数
if [[ ${true_pid} != “” ]] ---------这是里两个[] ,用此语句判断是否为空时,需要两个[]。

猜你喜欢

转载自blog.csdn.net/weixin_43466526/article/details/129087216