1

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?

3
  • Why are you trying to delete the files from your user's .Trash with sudo in the first place? Is your sudoers configuration set to NOPASSWD?
    – techraf
    Jan 7, 2017 at 23:58
  • @techraf Does running anything is Cron automatically grant sudo rights? if not, how can I run sudo rights within a Cron job?
    – MacMania
    Jan 8, 2017 at 0:06
  • I asked you two questions, please answer.
    – techraf
    Jan 8, 2017 at 0:07

2 Answers 2

1

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.

2
  • Thank you for the well explained answer! That makes sense and it worked!
    – MacMania
    Jan 8, 2017 at 4:11
  • re ~ ut is not a recommendation not to use it. It just does not work in cron
    – mmmmmm
    Jan 8, 2017 at 10:14
3

If you want to specify the the root user's crontab, you have to use the -u option.

sudo crontab -e -u root

That said, there's a safer way to clean out your trash than just removing the whole directory. Personally, I like to remove files that are older than a certain number of days. This way, if I inadvertently delete something today, I have a "buffer" of time in which to recover from.

The following command will delete all files that are older than 15 days.

find ~/.Trash/ -type f -mtime +15 -exec rm {} \;

Now...that said...

cron has been deprecated for launchd. I would take some time and learn how to create .plist XML files for lauchd and use that service instead of cron

1
  • This was super helpful as well!
    – MacMania
    Jan 8, 2017 at 4:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .