How to run a cron job using the sudo command

October 5, 2021 . 1 MIN READ

I won’t get into how much this is a bad idea; simply put, running sudoin crontab requires your password to be stored somewhere in plaintext.

It’s a bad idea.


The following is the preferred method of running administrative tasks through cron. Since you don’t really need to write sudo in the crontab, if you are modifying root’s crontab.

Use root’s crontab

Run the following command:

sudo crontab -e

This opens up root‘s crontab. sudo is not necessary to run your command in this context, since it’ll be invoked as root anyway.

Therefore, you would simply append the following to root’s crontab.

@hourly rm somefile

Now, if you absolutely want to be unsafe and take risks with your password, the following will run your command from your own crontab, and enter your password automatically when prompted by sudo.

Again, this is not recommended.


In your own crontab, write your command like so:

@hourly echo "password" | sudo -S rm somefile

The obvious disadvantage here is that, should anyone ever access your crontab, your password will be readable in plaintext.

Resource: https://askubuntu.com/questions/173924/how-to-run-a-cron-job-using-the-sudo-command

Read more: https://askubuntu.com/questions/2368/how-do-i-set-up-a-cron-job

Leave a Reply

Your email address will not be published. Required fields are marked *