18

I need to run a script daily. The script should be run as a specific user (ex. user1) not as root. So I put the cron file at /etc/cron.d and put the user name in the line (2nd column). But it gives an error saying that the command is not found. I suspect that the script was not run as user1's environment. Did I miss something?

31

Only /etc/crontab and the files in /etc/cron.d/ have a username field. In that file you can do this:

1 1 * * * username /path/to/your/script.sh

From root's crontab sudo crontab -e you can use:

1 1 * * * su username -c "/path/to/your/script.sh"

Or you can use the user's actual crontab like this:

sudo crontab -u username -e

The second column in any crontab file is for the hour that you want the job to run at. Did you mean the sixth field?

  • File in /etc/cron.d take a user argument: help.ubuntu.com/community/CronHowto#Advanced_Crontab and why are you doing "sudo su" if you're executing as root? In any case, you will want "su -l" to use the login environment for the user, since this is most likely a PATH issue, from the description of the problem. – cjc Jan 23 '12 at 18:55
  • Aren't the files in /etc/cron.d an extension of /etc/crontab ? On the systems I have to hand all the files in /etc/cron.d have a username specified. – user9517 supports GoFundMonica Jan 23 '12 at 18:56
  • Ah, indeed. /etc/cron.d/ files are part of /etc/crontab. sudo is also pointless. I'll remove that part. – Ladadadada Jan 23 '12 at 19:01
  • 2
    Regarding putting sudo in the crontab: (a) sudo su... is generally unnecessary; sudo -u <user> <command> is usually sufficient. (b) sudo will choke on some systems if there isn't a TTY attached (such as when run by cron). That can be fixed in your sudoers file. – tylerl Jan 23 '12 at 19:03
4

You may need to set the PATH for that user, if the executable you're using is in, say, /usr/local/bin. To set the PATH, put something like this before the cronjobs:

PATH=/bin:/usr/bin:/usr/local/bin

*/5 * * * * user1 sample_executable

The other way is to fully specify the path to sample_executable in your cronjob, so:

*/5 * * * * user1 /path/to/sample_executable

If sample_executable refers the executables not in the standard PATH, you should use the first option.

1

The typical directory for user crontabs is in /var/spool/cron/crontabs. The file format is the one that doesn't include the username. User crontabs are owned by the user and named after the user with mode 0600. This is best handled by writing your tab file and using crontab -u username filename to setup whatever cron entries you want for that user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.