Linux 開機自啟動機制隨發佈版演進已有多代:傳統 SysVinit (rc.d)、systemd 服務單元、用戶級 Shell 配置、定時任務等。本文系統梳理各層級配置方法,適用於 CentOS 6/7、Ubuntu 16.04+、Debian 9+ 等主流環境。
# 建立服務文件 /etc/systemd/system/myservice.service
[Unit]
Description=My Custom Service
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/myapp --config /etc/myapp.conf
Restart=on-failure
User=nobody
[Install]
WantedBy=multi-user.target
管理命令:
systemctl daemon-reload:重載配置systemctl enable myservice:設定開機自啟systemctl start myservice:立即啟動systemctl status myservice:查看狀態chkconfig --level 35 myservice onupdate-rc.d myservice defaults/etc/init.d/,需符合 LSB 標準(支援 start/stop/restart/status)大多數發佈版仍支援 /etc/rc.d/rc.local 或 /etc/rc.local(轉鏈)。
chmod +x /etc/rc.d/rc.local
echo "/usr/local/bin/startup.sh" >> /etc/rc.d/rc.local
注意:systemd 系統下需確保 rc-local.service 已啟用。
| 文件 | 生效範圍 | 說明 |
|---|---|---|
~/.bash_profile | 登入 Shell | 首選,僅登入時執行一次 |
~/.bashrc | 互動式 Shell | 每開啟終端執行,常放別名/函數 |
~/.profile | 圖形登入 | 非 Bash 登入 Shell 回退讀取 |
/etc/profile | 所有用戶 | 系統級環境變數,登入時執行 |
例:echo "synergyc 192.168.0.154" >> ~/.bash_profile
crontab -e
# 每天 03:00 備份
0 3 * * * /scripts/backup.sh >> /var/log/backup.log 2>&1
# /etc/systemd/system/backup.timer
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
配合同名 .service 啟用:systemctl enable --now backup.timer
echo "/scripts/onetime.sh" | at 23:59
atq # 查看隊列
atrm 1 # 刪除任務
~/.config/autostart/*.desktop/etc/xdg/autostart/Environment=PATH=...After=network-online.target + Wants=network-online.targetUser= Group=,避免 root 執行After= Requires=總結:系統服務用 systemd,用戶腳本用 ~/.bash_profile,定時任務用 systemd timer/cron,圖形程序用 .desktop,按場景選型最穩健。