fcm fcm - 5 months ago 12
Linux Question

crontab: which one is the right job definition?

Which one is the right definition for a

crontab
job?

With or without the
user
before the execution path?

.---------------- minute (0 - 59)
| .------------- hour (0 - 23)
| | .---------- day of month (1 - 31)
| | | .------- month (1 - 12) OR jan,feb,mar,apr ...
| | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
| | | | |
* * * * * <user> <command>


On Debian,
crontab -l
show a backup example as:

....
For example, you can run a backup of all your user accounts
at 5 a.m every week with:
0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
...


There is no
user
here!!

The
/etc/crontab
content (on the same box), gives a different clue:

....
and files in /etc/cron.d. These files also have username fields,
that none of the other crontabs do.
...

Answer

crontab does not * allow for specifying a user to run as...

... unless you're in the root crontab.

If you check my favorite linux admin reference, you'll not near the bottom that there are some tricks to running certain chrontab entries as a particular user. However, the best practice, if you wish to do so, would be to edit the crontab of the user:

crontab -u <username> -e

If you must...

0 0 * * * sudo -u [user] [command]

But this can only be done in the crontab of a user with sudo permissions, and as fcm pointed out, such a user could just edit the root crontab.

Most flavors of 'NIX require a user in the root crontab /etc/crontab

0 0 * * * [user] [command]

Conclusion

If you want to specify which user is running a specific cron job, the best practice is to do one of the following, depending on the use-case:

  1. root crontab
    • /etc/crontab
    • sudo crontab
    • <time> <user> <command>
  2. user crontab
    • crontab -u <username> -e
    • <time> <command>