在 Debian 及 Ubuntu 開機後, 如果想自動執行一些 shell script 或指令, 可以直接編輯 /etc/rc.local 檔案.
以下是 /etc/rc.local 預設內容:
|
1 2 3 4 5 6 |
#!/bin/sh -e # # rc.local - executed at the end of each multiuser runlevel # # Make sure that the script will "exit 0" on success or any other # value on error. |
要加入自動執行指令或 shell script 十分簡單, 只要直接加上要執行的指令即可, 例如我設定了每次開機會自動恢復 iptables 的設定, 便加入了 iptables-restore 指令:
|
1 2 3 4 5 6 7 8 |
#!/bin/sh -e # # rc.local - executed at the end of each multiuser runlevel # # Make sure that the script will "exit 0" on success or any other # value on error. /sbin/iptables-restore < /root/iptables-save |
儲存檔案後就完成了, 下次開機便會自動執行加入的指令.
————————————
11-Jun-2018 更新:
在 Ubuntu 16.10 及 17.10 已經沒有 /etc/rc.local 這個檔案了, 如果不想逐一透過 systemd 啟動服務, 可以用以下方法自行建立 /etc/rc.local:
建立啟動 /etc/rc.local 的 systemd 檔案, 這裡只設定執行 /etc/rc.local 的內容:
$ sudo vim /etc/systemd/system/rc-local.service
加入以下內容:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
[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 |
把上面的 rc-local 設定成開機自動執行:
$ sudo systemctl enable rc-local.service
執行以下指令建立 /etc/rc.local 檔案, 及給予可執行權限:
$ sudo touch /etc/rc.local
$ echo ‘#!/bin/bash\n’ >> /etc/rc.local
$ sudo chmod +x /etc/rc.local
$ echo ‘#!/bin/bash\n’ >> /etc/rc.local
$ sudo chmod +x /etc/rc.local
這樣就可以像以往一樣, 將要開機執行的指令放到 /etc/rc.local 檔案.
看你这个编辑器感觉好累的说,有没想过换一个啊
Ubuntu 17.10 OS預設內並沒有這個檔案