简体   繁体   中英

Linux cron job fails to execute part of script which works in shell

I'm having a problem with a script that writes to a log file during a backup procedure. Tested perfectly when called from the root shell, but fails when run from the cron demon.

Backup is done over a series of partitions and the on-site admin will rotate the drives in the top dock weekly. In order to know where the most recent backup is located I've included the following lines

sudo hdparm -I /dev/sdb | grep 'Model Number'
sudo hdparm -I /dev/sdb | grep 'Serial Number'

I've tried this with a >> /batch/backup.log and without. When the bash script is run from the command line, it works beautifully. But when the crontab calls the script the output from these lines is blank.

crontab entry: 00 00 * * * /batch/backup.bat >> /batch/backup.log

I have no idea why other than the possibility that cron can't handle the pipe or the grep or something.

I have isolated the lines in a test.bat but they remain blank.

The backup script uses the hdparm to spin down the drive at the end, but now I wonder if that's not working properly either if cron can't handle hdparm.

That is probably because hdparm is not in the PATH when the script is executed through cron. Although less likely, same might apply to grep as well.

Try replacing hdparm with /full/path/to/hdparm in your script.

You need to either put this in the root crontab, or you need to store your password in plain text and pipe it into the sudo command. That second option is obviously NOT RECOMMENDED. See https://askubuntu.com/questions/173924/how-to-run-a-cron-job-using-the-sudo-command

As @Paul hinted, it is also possible to create a directive in /etc/sudoers to override the need for a password for a specific user / host / command combination. See https://askubuntu.com/a/159009

Copying just a little bit from that answer:

If your user is called user and your host is called host you could add these lines to /etc/sudoers :

user host = (root) NOPASSWD: /sbin/shutdown 
user host = (root) NOPASSWD: /sbin/reboot

This will allow the user user to run the desired commands on host without entering a password. All other sudoed commands will still require a password.

Edit the crontab entry as below

00 00 * * * /batch/backup.bat 1> /batch/backup.op 2> /batch/backup.err

Standard output will be redirected to /batch/backup.op Standard error will be redirected to /batch/backup.err

Check the errors in /batch/backup.err and fix

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM