linux shell 编写开机启动启动jar包的脚本

通过编写一段shell脚本,让linux服务器能够在开机的时候启动某个jar包,因此,shell脚本初步得有三个功能

  • linux 字符串变量使用的四种方法
var=variable
var1=var1
var2=var2
str1="this is${var}" #和其他字符连接紧密的时候需要用{}隔开
str2=$var1$var2 #中间不能有空格
str3="$var1 $var2" #中间可以有空格
str4=$var1" "$var2
  • shell的类型
    sh,bash,ksh等
    本次的shell脚本是bash类型的
#!/bin/bash
  • 基本参数

    jar包路径
    端口id

#这里路径和端口都是固定的,可以更改为参数化设置
jarPath=""
xiongAnJarPath=""
servicePort=8081
  • 判断jar包绑定的端口是否被占用

    用最高的权限来查找占用的进程,并返回pid
    如果占用,则用最高的权限kill占用的

processId=`sudo netstat -lnp|grep ${servicePort} |awk '{print $7}'`
if [ $processId ];then 
        #delete the variables from the tail until the first, assign those to apid
        apid=${processId%/*}
        echo "the process number of port ${servicePort} is:$apid"
        #kill those processes
        sudo kill -9 $apid
        echo "kill the process which takes up the port ${servicePort}(pid:$apid)"
else
        echo "no process takes up the port ${servicePort}"
fi
  • 判断需要启动的jar包是否存在
  • 同时使用nohup记录标准输入和标准错误,要保证后台运行,以后可能会遇到nohup.out文件过大等问题,真遇到了再做打算
xiongAnParentDir=""
xiongAnlogPath="${xiongAnParentDir}nohup.out"
echo $xiongAnlogPath
startCommandXiongAn="nohup java -jar ${xiongAnJarPath} >> ${xiongAnlogPath} 2>&1 &"
startCommand="nohup java -jar ${jarPath} >> ${xiongAnlogPath} 2>&1 &"
#whether that the file exists or not
if [ -f ${xiongAnJarPath} ]||[ -f ${jarPath} ];
then
    if [ -f ${xiongAnJarPath} ] ;
    then
        echo "------${xiongAnJarPath} started------"
        $startCommandXiongAn
 
    fi
    if [ -f ${jarPath} ] ;
    then
        echo "------${jarPath} started------"
        $startCommand

    fi
fi
  • linux开机即启动脚本有如下几种方式

Linux—添加开机启动(服务/脚本)

将写好的shell放置到/etc/profile.d/ 目录下即可

  • 可以优化的点
    jar包的路径和端口可以作为参数配置写入脚本
    脚本是否需要启动一个进程判断jar服务是否活着,如果服务停了就开启
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值