How to run a cron job a different user

By: Shane Harter|Last Updated: Dec 09, 2023

Running cron jobs as another user is an advanced technique but one that is easy to master. This guide will take you beyond the comfort of crontab -e and show you how to use a system-wide crontab to schedule your job.

How to run a cron job as different user?

To run a cron job a different user, schedule the job in a system-wide crontab file, specifically by placing your own custom crontab file in /etc/cron.d, or adding your job to /etc/crontab. In a slight augmentation to the user crontab format, these system-wide crontabs have a user field after the schedule, and this will be used when the job is run. In this example, the job will be run as the user dataproc:

$ cat /etc/cron.d/my-custom-crontab
* 0 * * * dataproc /var/cronitor/bin/database-backup.sh

If you have just one or two jobs to schedule, it's quick and easy to just add them directly to /etc/crontab. If you have more jobs, it's better to organize them into their own crontab file and add it to the cron drop-in directory at /etc/cron.d. Note: either method will usually require root or sudo privileges.

To edit /etc/crontab, just open the file in vim or your editor of your choice. It looks correct but running sudo crontab -e edits the root user crontab, not the system-wide crontab, and that is an important distinction when you want to run a job as a different user.

Want alerts if your cron jobs stop working?

Monitor your cron jobs with Cronitor to easily collect output, capture errors and alert you when something goes wrong.

Editing another user's crontab

Another way to run jobs as a different user is to add them directly to their user crontab. This functionality is built-in to the crontab command, and as an administrator you may sometimes wish to see or edit another user's crontab file, but it's not the recommended way to schedule and run jobs as different users. It's much easier to find and maintain jobs over time if these jobs are centralized at the system-wide locations outlined in the previous section.

That said, if you are absolutely sure you just want to add a job to another user's crontab, here's how you do it:

$ crontab -u <username> -e