Ubuntu22.04使用/etc/rc.local开机启动程序

# 前言

因为在工作中,Ubuntu系统经常使用到开机启动,为了方便之后使用,特此介绍下如何使用/etc/rc.local来开机启动程序,步骤如下,针对Ubuntu20.04或Ubuntu22.04系统都有效。

  1. 使用root权限编辑/lib/systemd/system/rc-local.service,添加以下内容:
[Install]
WantedBy=multi-user.target  
Alias=rc-local.service
  1. 并赋予该文件权限:
sudo chmod 777 /lib/systemd/system/rc-local.service
  1. 使用root权限创建/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 "测试成功" > /home/test.log

exit 0
  1. 并赋予/etc/rc.local该文件执行权限:
sudo chmod +x /etc/rc.local
  1. 创建服务的软链接:
sudo ln -s /lib/systemd/system/rc-local.service /etc/systemd/system/ 
  1. 设置服务为开机启动:
sudo systemctl enable rc-local.service
  1. 检测服务状态:
sudo systemctl status rc-local.service
  1. 重启设备,检测是否成功。如果已经创建了文件/home/test.log,并写入内容测试成功,则说明已经成功。
小夜