Shell – Crontabbed shell script not able to create/write to a file

cronfilesshell-script

I have written a simple shell script to backup the tables in my DB using the mysqldump command. The command simply dumps the DB into a dbName.sql file. However, if the dbName.sql file doesn't already exists and I crontab this shell script, it doesn't work. What could be the reason? Are crontab scripts not permitted to create and write to files?

Best Answer

Cron jobs can be run as root or another specified user. If that user does not have the permission to write to the .sql file the job will fail.

If the file exist and it has write permission for the user running the job the file will be written.

if the file does not exist and the user does not have permission to create files in target directory, the job will fail.

I can typically say

sudo touch /var/log/foo.log
sudo chown my_username /var/log/foo.log

now I can say:

echo bar > /var/log/foo.log

but if the file does not exist it will fail, as I have no permission to create files in /var/log/.

So question becomes if the user running the job have the right to create files where ever the output from mysqldump is written.


Now if I set up a cron job to run a script with this:

date > /var/log/foo.log

every minute, I can add:

*  *    * * *   my-user-name  /path/to/script

to /etc/crontab. As I have no permission to create files in /var/log/ the cron daemon will send me an email when the job fails.

After 1 minute there are no file. I go to a terminal and type mail:

$ mail
>N  1 Cron Daemon        Sat Jan 31 05:15   19/731   Cron <user@host>    /path/to/script
? type
...

/path/to/script: line 3: /var/log/foo.log: Permission denied

OK. My bad. I create the file and chown it to me. Now all is OK.


Have a look at these as well:

Related Question