查看系统中的自动启动脚本

1
ls /lib/systemd/system  | grep rc-local.service

可以看到有 rc-local.service 这个文件

修改 rc-local.service 文件的权限

1
sudo chmod 777 /lib/systemd/system/rc-local.service

修改 rc-local.service 文件

1
vi /lib/systemd/system/rc-local.service

打开 ,可以看到有以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#  SPDX-License-Identifier: LGPL-2.1-or-later
#
# This file is part of systemd.
#
# systemd is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.

# This unit gets pulled automatically into multi-user.target by
# systemd-rc-local-generator if /etc/rc.local is executable.
[Unit]
Description=/etc/rc.local Compatibility
Documentation=man:systemd-rc-local-generator(8)
ConditionFileIsExecutable=/etc/rc.local
After=network.target

[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
RemainAfterExit=yes
GuessMainPID=no

增加以下内容:

1
2
3
[Install]
WantedBy=multi-user.target
Alias=rc-local.service

保存,退出

修改 /etc/rc.local 文件

查看系统中有无 /etc/rc.local 这个文件,没有则自己创建一个。
写入以下内容(清空文件中原有所有内容):

1
vi /etc/rc.local

demo :

1
2
3
#!/bin/sh
echo "看到这行字,说明添加自启动脚本成功。" > /usr/local/test.log
exit 0

赋予权限

1
sudo chmod +x /etc/rc.local

java:

1
2
3
4
5
6
7
8
9
#!/bin/sh

export JAVA_HOME=/usr/local/jdk1.8.0_201
export PATH=${JAVA_HOME}/bin:$PATH

mv /data/wwwroot/password-evaluation/log.log /data/wwwroot/password-evaluation/log_`date '+%Y%m%d_%H.%M.%S'`'.log'
nohup java -jar -Dserver.port=8060 -Dspring.profiles.active=uat /data/wwwroot/password-evaluation/password-evaluation-1.0.jar >/data/wwwroot/password-evaluation/log.log 2>&1 &

exit 0

run.sh

1
2
3
4
5
6
#!/bin/sh
export JAVA_HOME=/usr/local/jdk1.8.0_201
export PATH=${JAVA_HOME}/bin:$PATH

mv /data/wwwroot/password-evaluation/log.log /data/wwwroot/password-evaluation/log_`date '+%Y%m%d_%H.%M.%S'`'.log'
nohup java -jar -Dserver.port=8060 -Dspring.profiles.active=uat /data/wwwroot/password-evaluation/password-evaluation-1.0.jar >/data/wwwroot/password-evaluation/log.log 2>&1 &

rc.local

1
2
3
4
5
6
7
8
9
#!/bin/sh

#root用户启动
#sh /data/wwwroot/password-evaluation/run.sh

#非root用户启动 (chinagdn 替换成自己的用户名)
su - chinagdn -s /bin/bash /data/wwwroot/password-evaluation/run.sh &

exit 0

创建软链接

1
ln -s /lib/systemd/system/rc-local.service /etc/systemd/system/ 

重启

1
cat /usr/local/test.log

其他说明

如果在 /etc/rc.local 中添加的是 ./test.sh 这种类型的,要在末尾加上&,不然重启ubuntu的时候会卡在启动界面进不去系统。