Search code examples
linuxbashshellcron

Cron script doesn't work unless called by sh command


I have a script saved in file named file.sh It is executed by command

chmod +x file.sh

file.sh

#!/bin/sh
find /var/log/*.gz  -printf "%T@ %Tc %p\n"|sort -n|tail -n +6|sudo xargs rm|echo"test"|wall

I am trying to execute it by cron job.

Crontab

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
* * * * * root /etc/file.sh

Script is launched every minute by cron job, I am getting echo in terminal.

But xargs rm doest works . I do know why.

When I execute command sudo sh file.sh, is OK, and file is deleted.

Please help me find the reason why the script is not working in cron-job. It's strange.

Thank You !


Solution

  • The problem is your printf statement ... I'm fairly certain that you should also see error messages from rm in root's mail to the effect that e.g.: 1634986839.0000000000 Sun 24 Oct 2021 12:00:39 AM UTC /var/log/syslog.2.gz doesn't exist.