Running Cron Job w/ Sudo permissions

cronsudotrash

Strictly for learning purposes (possibly maintenance as well) I am trying to have a Cron job empty my trash once a day.

I have opened terminal and entered the command crontab -e to access the VI editor to add the command. I've entered Insert mode and added * * * * * sudo rm -rf ~/.Trash/*, hit the escape key to exit and quit VI with :wq!

This particular script I have running every minute just to see if it works and it is not. I thought it might be an issue with cron not having root access, so I added the same line to the sudo crontab -e file and it doesn't seem to be saving.

Any ideas what could be wrong with this cron job?

Best Answer

You think you need to use sudo. You don't. You're not trying to empty root's Trash folder. You have permission to delete files in your own ~/.Trash folder, so you don't need to become root (which is what sudo does) to do the rm.

You can simply use:

* * * * * rm -rf ~/.Trash/*

Note, I'd also advise against using ~ in a dangerous command like this (any time you're calling rm -rf it's potentially dangerous). Put the full path to the .Trash folder so it's very explicit what will happen when the line is executed. Something like /Users/yourusername/.Trash/. So:

* * * * * rm -rf /Users/yourusername/.Trash/*

Where you replace yourusername with your actual user name on the host.