13

I would like to set up a cron job that recusively does a chmod/chown on a directory (the dropbox directory).

This works when I execute the commands manually like:

sudo chown -R $USER ~/Dropbox
sudo chmod -R u+rw ~/Dropbox

I tried to convert it into a cron job like this:

10      *       *       *       *       sudo chown -R $USER ~/Dropbox

But it doesn't seem to do the job.

How to do this?

user9517
  • 117,122
tvgemert
  • 277
  • 1
  • 2
  • 7

5 Answers5

17

sudo should almost never be used in scheduled tasks. It expects to be able to talk to a terminal, and requires specific flags to avoid trying to do so.

Create your cron job as root (in /etc/crontab - Note that the format of this file is slightly different: minute hour mday month wdayusercommand) instead.
This also has the benefit of working on systems where sudo isn't installed.

voretaq7
  • 80,749
14

You want your root cron script (edit by running sudo crontab -e) to be:

 55 * * * * /bin/chown -R somename /home/somename/Dropbox && /bin/chmod u+rw /home/somename/Dropbox

Assuming the user is named somename and that /home/somename/Dropbox is the full path of your Dropbox directory. As root user, ~ goes to /root.

dr jimbob
  • 409
6

Two issues:

1) Paths aren't normally set up in cron the same way they are when you log in. Try /usr/bin/sudo /bin/chown ... (or whatever the right paths are to those programs on your system).

2) sudo normally asks for your password, or may otherwise not be happy running noninteractively. I suggest you put the commands in root's crontab without the sudo instead, then the commands run as root.

pjc50
  • 1,740
6

There are multiple issues with your crontab:

10 * * * sudo chown -R $USER ~/Dropbox

The issues:

  • sudo should not be used here; it requires terminal input
  • chown should be fully specified (i.e., /bin/chown)
  • USER as an actual variable may not exist; some systems use LOGNAME
  • ~ (tilde) will only be recognized by a shell - a bare chown will not understand it
  • specifying HOME in root's crontab goes to root's home

I think I'd actually script it:

#!/bin/bash

# FILE: /usr/local/bin/myscript

USER=$1
eval chown -R $1 ~$1/Dropbox
eval chmod -R u+rw ~$1/Dropbox

(The eval is needed to convert ~$1 to ~user then to /home/user.)

Run this script from root's crontab:

# root's crontab
10 * * * /usr/local/bin/myscript someuser
Mei
  • 4,620
0

As an alternative, you might be able to enable ACL support and use setfacl to achieve the same/similar result.

Ryan D
  • 21