Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux Crontab 定時任務 Shell 腳本不執行?環境變數缺失排查與修正

編輯:關於 Linux

Crontab 執行環境極度精簡,缺少互動式 Shell 的 PATH、HOME 等環境變數,導致腳本找不到指令而靜默失敗。解決核心在於腳本開頭顯式匯入環境變數或使用絕對路徑。本文提供標準修正範例與常見排程語法速查。

Crontab 環境變數示意圖

根因分析

  • Cron 執行時 PATH=/usr/bin:/bin,無 /usr/local/bin、/opt/... 等自訂路徑
  • 無 HOME、USER、SHELL 等變數,導致 ~ 展開失敗
  • 標準輸出/錯誤預設郵件給擁有者,若未配置郵件系統則完全無日誌

修正方案

方案一:腳本開頭匯入 PATH (推薦)

#!/bin/bash
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# 其餘腳本內容...

方案二:腳本內所有指令使用絕對路徑

/usr/bin/docker pull nginx
/opt/backup/bin/backup.sh

方案三:在 crontab 行內設定環境

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
0 2 * * * /root/backup.sh >> /var/log/backup.log 2>&1

Crontab 語法速查

# 格式:分 時 日 月 週 指令
* * * * *  每分鐘執行
0 * * * *  每小時整點
0 2 * * *  每天 02:00
*/20 6-12 * * *  每天 06:00-12:00 每 20 分鐘
0 17 * * 1-5  週一至週五 17:00
20 0-23/2 * * *  每天 00:20, 02:20, 04:20...
@reboot  開機執行一次
@daily   每天 00:00 (等同 0 0 * * *)

除錯技巧

  1. 重導向輸出到日誌:> /var/log/myscript.log 2>&1
  2. 測試環境變數:* * * * * env > /tmp/cron_env.txt 比對互動式 env 差異
  3. 確認 cron 服務運行:systemctl status cron / systemctl status crond
  4. 檢查腳本權限:chmod +x /path/script.sh、Shebang 正確 #!/bin/bash
Copyright © Windows教程網 All Rights Reserved