在传统的 SysV init (早期 Linux/Unix 使用的传统启动和服务管理系统) 系统中, Linux 管理员和开发者常通过 /etc/rc.local
脚本在系统进入多用户运行级别 (multi-user runlevel) 时执行自定义命令。然而, 在使用 systemd 的现代 Linux 发行版中, /etc/rc.local
默认被禁用。
本文介绍如何在 systemd 中启用并执行 /etc/rc.local
在 systemd 中启用 rc.local 脚本的方法
systemd 提供了一个特殊的单元 (unit) rc-local.service
, 它会在多用户目标 (multi-user.target) 时自动调用 /etc/rc.local
, 前提是该文件存在并且可执行。
创建和配置 /etc/rc.local
编辑 /etc/rc.local
文件 (不同发行版路径可能略有不同)
# Debian / Ubuntu
vim /etc/rc.local
# RHEL / CentOS / Fedora
vim /etc/rc.d/rc.local
添加需要的命令, 例如
#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.
# 设置 Wi-Fi 唤醒
/sbin/iw phy0 wowlan enable magic-packet disconnect
使用 :wq
保存文件并赋予可执行权限
chmod +x /etc/rc.d/rc.local
启用 rc.local 服务
首先检查 rc-local 服务是否已启用
systemctl is-enabled rc-local.service
如果结果为 disabled
或 static
, 说明服务未启用, 需要手动开启
systemctl enable rc-local.service
然后重启系统, 并验证服务状态
systemctl status rc-local.service
正常情况下会显示服务已启动并退出 active (exited)
查看 rc-local.service 配置
使用以下命令可查看完整配置
systemctl cat rc-local.service
典型配置示例
# /usr/lib/systemd/system/rc-local.service
# 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.d/rc.local is executable.
[Unit]
Description=/etc/rc.d/rc.local Compatibility
ConditionFileIsExecutable=/etc/rc.d/rc.local
After=network.target
[Service]
Type=forking
ExecStart=/etc/rc.d/rc.local start
TimeoutSec=0
RemainAfterExit=yes
关于运行级别 (Runlevel)
在 SysV init 时代, 常见 运行级别 如下
运行级别 | 含义 |
---|---|
0 |
关机 |
1 |
单用户模式 (在紧急模式下恢复 Linux 系统) |
2 to 5 |
多用户模式 (支持 CLI/GUI/网络) |
6 |
重启 |
/etc/rc.local
通常在进入多用户运行级别 (2–5) 时执行。随着大多数 Linux 发行版切换到 systemd, 该机制已被弃用, 如需使用需通过前述方法手动启用。
使用自定义 systemd 服务 (推荐做法)
相比 rc.local
, 直接编写 systemd 服务单元更符合现代 Linux 习惯。
示例模板, /etc/systemd/system/my-service.service
[Unit]
Before=network.target
[Service]
Type=oneshot
ExecStart=/path/to/command
ExecStart=/path/to/script arg1 arg2
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
启用服务
systemctl enable my-service.service
systemctl start my-service.service
原文
How to enable rc.local shell script on systemd while booting Linux system