通过编写一段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开机即启动脚本有如下几种方式
将写好的shell放置到/etc/profile.d/ 目录下即可
- 可以优化的点
jar包的路径和端口可以作为参数配置写入脚本
脚本是否需要启动一个进程判断jar服务是否活着,如果服务停了就开启