利用linux shell脚本 重启tomcat

时间:2021-08-11 21:59:57

在工作中遇到要使用ps -ef | grep tomcat6 来进程ID并kill掉后重启tomcat的场景

killRestart.sh

===============

#!/bin/bash
tomcat6pid=`ps -ef|greptomcat6|grep-v"grep"|awk'{if($17=="-Dcatalina.home=/home/leekim/tomcat6"){print $2}}'`
echo "$(date '+%Y-%m-%d %H:%M:%S')tomcat6 pid before kill is" $tomcat6pid >> /home/leekim/log/restartlog.txt

if [ $tomcat6pid != ""]; then
   kill -9 $tomcat6pid
   echo "$(date'+%Y-%m-%d %H:%M:%S') kill -9" $tomcat6pid>> /home/leekim/log/restartlog.txt
   sleep 6
fi
tomcat6pid=`ps -ef|greptomcat6|grep-v"grep"|awk'{if($17=="-Dcatalina.home=/home/leekim/tomcat6"){print $2}}'`
if [ "$tomcat6pid" = "" ]; then
   /home/leekim/tomcat6/bin/startup.sh
   tomcat6pid=`ps -ef|greptomcat6|grep-v"grep"|awk'{if($17=="-Dcatalina.home=/home/leekim/tomcat6"){print $2}}'`
   echo "$(date'+%Y-%m-%d %H:%M:%S')tomcat6 startup, new pid is " $tomcat6pid >> /home/leekim/log/restartlog.txt
elif [ "$tomcat6pid" !=""]; then
   echo "$(date '+%Y-%m-%d %H:%M:%S')tomcat6 kill -9 failure, pid is"$tomcat6pid>>/home/leekim/log/restartlog.txt
fi


注意:

1. $17具体是什么值,请根据自己的真实环境配置,总会有个条件来过滤判断的,可能是$13、$14等等

2. awk中代码用{}括起来

    awk '{print $2}'

    awk '($17=="xxx"){print $2}'

    awk '{if($17=="xxx"){print $2}}'

3. shell变量赋值等号左右两边没有空格

    test=1

4.shell中if判断(=判相等,注意if和then之间的条件判断格式,主要是空格之类的)

    if [ xx != "" ]; then

       echo "xx"

    fi

   或

    if [ xx != "" ]; then

       echo "11"

    elif [ xx = "" ]; then

       echo "22"

    else

       echo "33"

     fi

5.如果在使用变量的行出现类似信息“第 10 行: [: =: 期待一元表达式”

  多半是因为要变量外没有使用双引号

  错误:if [ $test = "abc" ]; then

  正确:if [ "$test" = "abc" ]; then


定时任务

========

crontab -e

0 5 * * * /home/leekim/killRestart.sh