michabbb
michabbb

Reputation: 931

How to check cron syntax by script like "crontab -e" does?

Let's say I write cron files via script and modify them direct under /var/spool/cron/crontabs/. When using the command crontab -e crontab checks the syntax when I exit the editor. Is there any way to do the same check via script?

Upvotes: 12

Views: 19023

Answers (4)

Dee Newcum
Dee Newcum

Reputation: 1030

Blashser's answer is good, but it creates a small risk of making problematic changes to the system-wide cron.

This variant below leverages the fact that each user has their own personal crontab settings. If you have a mostly-unused user on the system (e.g. a printer daemon or webserver account) whose crontab is empty, you can temporarily use their crontab, and avoid touching the system-wide one.

Su to that user:

sudo -i -u $USER

Double-check that their crontab is empty:

crontab -l

Set this user's crontab to the one we want to check, and watch for any error messages:

crontab /etc/cron.d/syntax_check_me

Restore this user's original crontab by clearing it:

crontab -r

The only caveat is that there's a user field that can be used in individual cron rules, but only in the system-wide cron. So testing it this way would throw an error if the extra user field is present.

Upvotes: 0

Mohamad Hamouday
Mohamad Hamouday

Reputation: 2753

Export your current crontab to a new file if you don't have it:

crontab -l > mycron.cron

Next, execute this command to verify the syntax:

crontab -n mycron.cron

output:

The syntax of the crontab file was successfully checked.

Upvotes: -1

Use chkcrontab:

pip3 install chkcrontab
chkcrontab /etc/cron.d/power-schedule
Checking correctness of /etc/cron.d/power-schedule
E: 15: 0 12 * foo * * root echo hi
e:     FIELD_VALUE_ERROR: foo is not valid for field "month" (foo)
e:     INVALID_USER: Invalid username "*"
E: There were 2 errors and 0 warnings.

Or try a shell script 48-verifycron from Wicked Cool Shell Scripts, 2nd Edition, but it's not as good.

Upvotes: 4

blashser
blashser

Reputation: 1031

Crontab with -e option does open your default editor with the current cron file and installs it after exiting.

First of all, save your actual cron file to be sure of not losing or breaking anything.

crontab -l > backup.cron

You can directly install a file that you have cooked:

crontab yourFile.text

Or use a pipe in a script:

#/bin/bash
Variable="your scheduled tasks"
echo $Variable | crontab

You will get the error messages in the case of bad formatting.

More info: man crontab

Upvotes: 9

Related Questions