本文适用的Ubuntu版本有18.04, 20.04, 其他版本未测试
一、 前言
添加开机启动项的背景与树莓派(Ubuntu IoT 20.04)有关, 是为了让它开机之后连接wifi并且启动ssh服务端, 经测试成功
二、 步骤
执行命令
1
$ ls /lib/systemd/system
可以看到很多启动脚本, 我们需要修改的是rc.local.service
, 使用vim编辑
1
$ sudo vim /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+
#
# 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
- [Unit]段: 启动顺序与依赖关系
- [Service]段: 启动行为,如何启动,启动类型
- [Install]段: 定义如何安装这个配置文件,即怎样做到开机启动
我们只需添加[Install]段就可以了
1
2
3
[Install]
WantedBy=multi-user.target
Alias=rc-local.service
下面在/etc/rc.local
中写入自己的脚本 (默认没有这个文件,创建即可)
1
$ sudo vim /etc/rc.local
1
2
3
4
5
6
7
8
9
10
#!/bin/sh -e
#
# rc.local
sudo echo "配置开机脚本成功" > /usr/local/test.log
#
# 在中间插入你的开机脚本
# 不能阻塞进程, 否则开机卡死
#
exit 0
记得为rc.local
添加执行权限
1
$ sudo chmod +x /etc/rc.local
还需要在/etc/systemd/system
目录下创建软链接
1
$ sudo ln -s /lib/systemd/system/rc.local.service /etc/systemd/system/
重启后在/usr/local/test.log
中看到文字说明设置成功