Search code examples
linuxbashshellcron

cron not running a bash script that uses date


I'm testing a script that executes sub-scripts for the daily rotation of logging files:

59 23 * * * /home/[username]/work/Rotate.sh

this .sh file calls a number of other shell scripts, each of them working similarly to this:

folderName=$(date +%B)
folderPath="/data/logs/archive/"
currentDate=$(date +%d-%m-%Y)
targetFile="/data/logs/logfile.log"

sudo mkdir $folderPath
sudo mkdir $folderPath$folderName

cp $targetFile $folderPath$folderName/logfile.$currentDate.log

echo "" > $targetFile

Directly calling Rotate.sh from terminal works as intended (using the command sudo sh work/Rotate.sh), but when I've reduced the crons timing to shorter intervals I haven't gotten any results at all. Is it possible that some aspect of my shell script is breaking the cron job? Have I missed something in the declaration of the line in crontab -e?


Solution

  • The common reason for such failures is because your CRON Environment is the bare minimum environment supported by system. Its not aware of additional environment settings which is made available to you via shell.

    A easy work around in such cases is to source .profile from your Shell Script. Putting below command at start of your file must help you to get this resolved.

    source $HOME/.profile
    

    Another way to do this would be to source the same in CRONJOB itself.

    59 23 * * * . $HOME/.profile; /home/[username]/work/Rotate.sh