首頁·終端機命令

crontab

行程與系統

用法

crontab -e | crontab -l

管理每個使用者的定時任務表;cron 執行時 PATH 幾乎是空的,也不會讀登入設定,所以路徑要寫絕對路徑,而 `crontab -r` 會不問一聲刪掉整張表。

常用選項

選項含義
-eEdit your table in $EDITOR; it is installed when you save.
-lPrint your table. Redirect it somewhere to keep a backup.
-rDelete the whole table at once, with no confirmation.
-u <user>Work on another user's table (root only).
m h dom mon dowThe five time fields, then the command. * means every.
@reboot / @dailyShorthand instead of the five fields.

範例

crontab -l > ~/cron.bak

Back up the table before touching it.

crontab -e

Then add: 0 3 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1

crontab -l | grep -v backup.sh | crontab -

Remove one line without opening an editor.

看什麼在跑、什麼在吃機器。先弄清是什麼,再決定殺不殺。

怎麼看

  • 方括號 [ ] 表示這部分可以不寫。
  • 省略號 … 表示可以寫多個。
  • 選項區分大小寫——有些命令裡 -r 和 -R 不是一回事。

常見問題

Q. crontab 是做什麼的?

管理每個使用者的定時任務表;cron 執行時 PATH 幾乎是空的,也不會讀登入設定,所以路徑要寫絕對路徑,而 `crontab -r` 會不問一聲刪掉整張表。

Q. 怎麼寫?

crontab -e | crontab -l —— 方括號表示可以省略的部分。

Q. 值得記的選項有幾個?

這裡列了 6 個,完整列表在 man crontab。這條命令屬於行程與系統。

相關命令

man 手冊: man crontab