I have a Shell script like below
echo "Hello World"
The script is located in /root/scripts/
folder as test.sh
I also created a cron job like below
0-59 * * * * ./scripts/test.sh
Now the cron job is not printing the content in test.sh
every minute.
Let me know whether I have given a wrong directory or I have any other problem in my code.
I would
/root/scripts/test.sh
. I don't know what cron would regard as the current directory...test.sh > /tmp/cron.log
(you would likely want to redirect stderr at some stage too using 2>&1
). Otherwise you're not going to see the output. It gets mailed to the cronjob ownerchmod +x /root/scripts/test.sh
)#!/bin/sh
or similarGetting stuff to run under cron is notoriously tricky. Cron jobs run with a massively cut-down environment. It's instructive to print out the environment available to your script (use env
) and compare/contrast with what you have available from your interactive shell.
A common problem encountered by new unix users when using cron to launch scripts is that their cronjobs do not have access to the same environment as their user shell. So a script executed in a user's shell works perfectly, but fails when launched from cron. The number one culprit in this case is that your shell's $PATH environment variable differs from that of cronjob's shell.
To test run '/bin/echo $PATH > myShellPath'. In cron run '/bin/echo $PATH > myCronPath'. Compare myShellPath with myCronPath.
In the example provided the script executes echo, which on my CENTOS6 system is found under /bin. The echo command is found by the shell by searching for the 'echo' file in one of the directories listed in the $PATH environment variable. If your cronjob's $PATH environment variable does not include /bin, the echo command will fail.
If this is the problem, the simplest solution is to explicitly set the path to 'echo' in your script. To view your system's full path for echo, type 'which echo' at your shell.
Example:
[countChocula@bozo ~]$ which echo
/bin/echo
In this case you would edit the script and replace 'echo' with '/bin/echo'. Better still, set the $PATH variable in your script to include the directory in which echo resides.
For further information, research "what shell am i running and how are my environment variables set?", "what shell is cron using and how do i set cron environment variables?", "how to view my cronjob's environment variables?"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With