Linux啟停java程式腳本
備注:本腳本是根據網上其他部落格的腳本修改而來。
#!/bin/sh
BASE_PATH=/data1/app/start-jar/test/
APP_NAME=demo-0.0.1-SNAPSHOT.jar
APP_LOG="log.log"
APP_PATH=${BASE_PATH}${APP_NAME}
#檢查程序是否已經在運作,如果在運作則傳回1,否則傳回0
is_exist()
{
pid=`ps -ef | grep -w "${APP_NAME}" | grep -v "grep" | awk '{print $2}'`
if [ -z "${pid}" ]
then return 1
else
return 0
fi
}
# 列印程序的狀态資訊
status()
{
is_exist
if [ $? -eq "0" ]
then echo "${APP_NAME} is running. pid=${pid} ."
else
echo "${APP_NAME} is not running"
fi
}
# 啟動程序
start()
{
is_exist
if [ $? -eq "0" ]
then echo "${APP_NAME} is already running. pid=${pid} ."
return 0
else
echo "try to start ${APP_NAME} ... "
nohup java -jar ${APP_PATH} > ${APP_LOG} 2>&1 &
# 程式的啟動需要一定的時間,這裡設定暫停時間(3秒),機關是秒
sleep 3
is_exist
if [ $? -eq "0" ]
then
echo "${APP_NAME} is running now. pid=${pid}."
return 0
else
echo "failed to start ${APP_NAME}! see ${APP_LOG} for more details."
return 1
fi
fi
}
# 停止HelloWorld程序
stop()
{
is_exist
if [ $? -eq 0 ]
then echo "try to stop ${APP_NAME} ..."
kill -9 ${pid}
if [ $? -ne 0 ]
then echo "failed to stop ${APP_NAME}!"
return 1
else
echo "${APP_NAME} stopped."
return 0
fi
else
echo "${APP_NAME} is not running!"
return 1
fi
}
# 重新開機HelloWorld程序
restart()
{
stop
start
}
# 顯示幫助資訊
help()
{
echo "status show the status of ${APP_NAME} server."
echo "start start the ${APP_NAME} server."
echo "stop stop the ${APP_NAME} server."
echo "restart restart the ${APP_NAME} server."
}
# 主函數
main()
{
case "$1" in
status)
status;;
start)
start;;
stop)
stop;;
restart)
restart;;
help)
help;;
*)
echo "command param error ! see follow help ";
help;;
esac
}
# 執行主函數 $1表示選擇第一個字元串為參數,比如終端指令是:./run.sh start status,則選擇start為輸入參數
main $1