Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux 開機自動執行自訂腳本完整教學(SysV init / chkconfig)

編輯:Linux 系統常見問題解答

前言

在 CentOS 6 / RHEL 6 等使用 SysV init 的系統上,將自訂腳本加入開機自啟動的標準流程:編寫符合規範的 init 腳本 → 放入 /etc/init.d/ → chkconfig --add 註冊。

實作範例:Coreseek 搜尋服務自啟動

1. 建立腳本檔

# vim /etc/init.d/auto_coreseek.sh

內容如下:

#!/bin/sh
# chkconfig: 2345 80 90
# description: auto start coreseek searchd

/usr/local/coreseek/bin/searchd

關鍵標註說明:
- # chkconfig: 2345 80 90
2345:在執行等級 2、3、4、5 啟動(多用戶/圖形模式)。
80:啟動優先序(數字越小越早)。
90:關機停止優先序(數字越小越早停止)。
- # description: 服務描述,供 chkconfig --list 顯示。

2. 賦予執行權限並註冊

chmod +x /etc/init.d/auto_coreseek.sh
chkconfig --add auto_coreseek.sh

3. 驗證

chkconfig --list auto_coreseek.sh
# 輸出應包含 2:on 3:on 4:on 5:on

# 手動測試
service auto_coreseek.sh start
service auto_coreseek.sh status

執行等級對照表

等級名稱說明
0關機系統停止
1單用戶維護模式
2多用戶無網路命令列模式
3多用戶有網路標準伺服器模式
4保留通常未使用
5圖形介面桌面環境
6重啟重新開機

優先序(Priority)觀念

  • 啟動時:數字**越小越先執行**(如網路服務 10,應用服務 80)。
  • 關機時:數字**越小越先停止**(先停應用,再停資料庫,最後停網路)。
  • 建議:依賴關係決定順序,避免競態條件。

systemd 時代的對應做法(CentOS 7+)

新版系統請改寫為 systemd unit 檔:

# /etc/systemd/system/coreseek.service
[Unit]
Description=Coreseek Search Daemon
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/coreseek/bin/searchd
ExecStop=/usr/local/coreseek/bin/searchd --stop
User=coreseek

[Install]
WantedBy=multi-user.target

啟用:

systemctl daemon-reload
systemctl enable coreseek
systemctl start coreseek

結語

掌握 SysV init 腳本規範與 chkconfig 操作,是維護舊版 Linux 系統的基本功;新系統請直接採用 systemd,更強大且標準化。

Copyright © Windows教程網 All Rights Reserved