-1

EDIT:My script is located at $HOME folder.This is the reason of the issue.More details by the end of the question.In any case,this is not a duplicate question!

I have a quite trivial script deleting some log files.Running perfectly from command line. However,If I install it on crontab,sporadically I get

/bin/sh: 1: $MyScript.sh: not found

I thought that might be related with crontab config so I have installed it into crontab specifically for my user via

sudo vi /etc/crontab

Unfortunately I still keep getting the same error intemittently. Below is my script.

#!/bin/sh
NOW=$(date +"%m-%d-%Y-%T")
echo "$NOW Starting deleting of  log files"
find /$PATH_TO_DIR/logs/* -mtime +30 -type f -delete

if [ $? -eq 0 ]
then
 echo "$NOW Successfully deleted files"
else
 echo "$NOW Could not delete files"
fi

Any help appreciated.

EDIT: Issue was my home folder being encrypted.That is why it was intemittently working,only when I was logged in to terminal.(Then home folder is decrypted and my schript is found). So I moved my script to somewhere else and it started working.

selman
  • 103
  • 3

1 Answers1

0

There are several issues:

crontabs (whether crontab -e or files in /etc/cron.d are specified as follows:

17 *    * * *   root    /usr/local/bin/script.sh

This example runs on th 17th minute of every hour, as root.

You can, however, put normal scripts in /etc/cron.daily/ (or weekly, monthly, hourly). Note: don't put a . in the filename then, it will be skipped.

Your script also references undefined variables. This will result in the path /logs/* being used, because $PATH_TO_DIR evaluates to empty. You could fix that by running set -u somewhere at the start of your script (disclaimer: I don't know how non-bash shells deal with that).

I also think we're missing information, because I don't see any reference to $MyScript

Halfgaar
  • 7,921
  • 5
  • 42
  • 81
  • $PATH_TO_DIR and $MyScript are placeholders for folder and scriptname,which I don't want to disclose since they include company/product name. So they are all fine. As to the crontab,I have added the line below using "sudo vi /etc/crontab" `0 6 * * * myuser path_to_my_script.sh >> /tmp/deleteOldLogoutput.txt 2>&1` What is wrong with this set up? – selman Dec 04 '17 at 13:08
  • If you have clarifying comments, edit your original question. The comment box is made layoutless on purpose. – Halfgaar Dec 04 '17 at 22:43
  • No need for clarification for this regard. I have edited the question with the solution. – selman Dec 05 '17 at 10:01