The shell script determines whether the process exists, kills and restarts the process

There are two ways

1. Method 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. Method 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 &

Remarks:
grep -v means reverse search, for example, grep -v "grep" is to find lines that do not contain grep fields.
wc -l is the number of statistical lines
if [[ ${true_pid} != "" ]] ---------This is two [], when using this statement to judge whether it is empty, two [] are required ].

Guess you like

Origin blog.csdn.net/weixin_43466526/article/details/129087216