方法很简单,在/etc/下建一个rc.local文件就行,以下就是理由。
---------------------------------
1,前言
玩过早一点的linux的人会发现在/etc或者在/etc/rc.d目录下有一个rc.local文件,现在没了。某种程度上应该算有的,事情的原因起因于一个叫systemd的东西,这个sytemd取代了(system v)init的父进程身份,说是改良了init的一些缺点。至于两者的区别,可参阅(https://www.ibm.com/developerworks/cn/linux/1407_liuming_init3/index.html),写的很详细。
2,查看
注意那句注释语句(if /etc/rc.local is executable)。
guoyanzhang@bogon:~$ cat /lib/systemd/system/rc.local.service
# 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
3,新建
从上面可以看到新建一个rc.local,就可以添加自己要开机执行的文件了。
guoyanzhang@bogon:~$ sudo cat /etc/rc.local
[sudo] guoyanzhang 的密码:
#!/bin/bash
cd /home/guoyanzhang/os
mkdir rclocal
4,补充
自systemd取代init之后,都是以服务的方式来执行脚本。
start:
guoyanzhang@bogon:~$ systemctl start rc-local
guoyanzhang@bogon:~$ systemctl status rc-local
● rc-local.service - /etc/rc.local Compatibility
Loaded: loaded (/lib/systemd/system/rc-local.service; enabled-runtime; vendor preset: enabled)
Drop-In: /lib/systemd/system/rc-local.service.d
└─debian.conf
Active: active (exited) since Sat 2019-01-19 23:15:30 CST; 26min ago
Docs: man:systemd-rc-local-generator(8)
Process: 877 ExecStart=/etc/rc.local start (code=exited, status=0/SUCCESS)
stop:
guoyanzhang@bogon:~$ systemctl stop rc-local
guoyanzhang@bogon:~$ systemctl status rc-local
● rc-local.service - /etc/rc.local Compatibility
Loaded: loaded (/lib/systemd/system/rc-local.service; enabled-runtime; vendor preset: enabled)
Drop-In: /lib/systemd/system/rc-local.service.d
└─debian.conf
Active: inactive (dead) since Sat 2019-01-19 23:42:45 CST; 11s ago
Docs: man:systemd-rc-local-generator(8)
Process: 877 ExecStart=/etc/rc.local start (code=exited, status=0/SUCCESS)
参考1:https://www.cnblogs.com/flymeng/p/7901062.html
参考2:http://blog.51cto.com/cakong/1618364