Ubuntu 18.04 设置开机启动脚本

1、建立rc-local.service文件并编辑

sudo vi /etc/systemd/system/rc-local.service
[Unit]
Description=/etc/rc.local Compatibility
ConditionPathExists=/etc/rc.local
 
[Service]
Type=forking
ExecStart=/etc/rc.local start
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99
 
[Install]
WantedBy=multi-user.target

2、创建rc.local并编辑

sudo vi /etc/rc.local
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
echo "看到这行字,说明添加自启动脚本成功。" > /usr/local/test.log
exit 0

3、给rc.local加上权限,启用服务

sudo chmod +x /etc/rc.local
sudo systemctl enable rc-local

4、启动服务并检查状态

sudo systemctl start rc-local.service
sudo systemctl status rc-local.service

5、检查是否生效

cat /usr/local/test.log

因为在rc.local里加了一句

echo "看到这行字,说明添加自启动脚本成功。" > /usr/local/test.log

所以如果成功执行会生成test.log并写入上面的内容。

想要其他脚本开机启动编辑rc.local即可

后记

我本来是想要开机启动泰拉瑞亚服务器的,但是用这种方法没有成功。先是提示Failed to start /etc/rc.local Compatibility 不知道为什么(可以参考https://blog.csdn.net/woay2008/article/details/92252232)可能#!/bin/bash后面的参数有影响,但我改过之后还是不行,有空了解一下这第一行的这个东西有什么用,我一直以为就是一个注释。

后来直接在rc.local里写启动命令,而不是放在脚本里,还是不行,这次是泰拉瑞亚服务器报错,抛出异常。

所以到最后我还是没解决这个问题,不知道为什么。

将泰拉瑞亚服务器启动命令换为下面的就成功了

/usr/bin/screen -dmS terraria /bin/bash -c "/opt/terraria/TerrariaServer.bin.x86_64 -config /opt/terraria/serverconfig.txt"

这个命令是在泰拉瑞亚论坛一个老哥提到的,是linode的一个教程(这年头卖服务器还得搞这种教程,该说是良心呢,还是被迫无奈呢)

所以问题是直接执行启动服务器命令不行,但是放到一个screen里就可以了。不知道为什么

参考文章:

https://www.jianshu.com/p/79d24b4af4e5

https://forums.terraria.org/index.php?threads/server-crash-with-system-nullreferenceexception.55032/

https://www.linode.com/docs/game-servers/host-a-terraria-server-on-your-linode/

原文地址:https://www.cnblogs.com/roadwide/p/12673229.html