1. 程式人生 > 其它 >轉:Shell 獲取Tomcat程序號

轉:Shell 獲取Tomcat程序號

一臺伺服器上部署了多個tomcat例項,要獲取名為 my_tomcat 的專案程序id,可以用如下命令

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

命令解析:
1、ps -ef | grep my_tomcat 獲得了程序資訊中包含 my_tomcat 的程序資訊
2、第一步查出來的結果中會包含grep本身,所以我們需要用 | grep -v grep 來排除grep本身
3、通過 awk '{print $2}'來打印出要找的程序
4、如果我們要刪除該程序,可以用如下命令

ps -ef | grep my_tomcat | grep -v grep | awk '{print $2}'| sed -e "s/^/kill -9 /g" | sh -

5、如果我們需要通過命令列刪除指定的專案,可以把指令碼修改如下

#!/bin/bash
echo "kill tomcat程序";
echo "檔名:$0";
 
if  [ ! -n "$1" ]
then
    echo "請輸入要刪除的tomcat專案關鍵字"
else
    echo "輸入的關鍵字為:$1";
    tomcat_id=$(ps -ef |grep tomcat |grep -w $1|grep -v 'grep' |awk {'print $2'})
    echo "查詢到的Tomcat專案程序id:$tomcat_id,開始刪除程序"
    kill -9 $tomcat_id
    sleep 5
    tomcat_id=$(ps -ef |grep tomcat |grep -w $1|grep -v 'grep' |awk {'print $2'})
    echo "重啟後的新程序id:$tomcat_id"
fi

測試一下:

sh restart.sh tomcat1
kill tomcat程序
檔名:restart.sh
輸入的關鍵字為:tomcat1
查詢到的Tomcat專案程序id:4161413,開始刪除程序
重啟後的新程序id:4161827

轉載 https://www.codeleading.com/article/6851370854/