Unix/Linux Go Back    

Can run a ".sh" script as the user but not from the crontab

Shell Programming and Scripting

Kindly Note - This is a Single User Post by Forum Member bakunin Regarding:
Can run a ".sh" script as the user but not from the crontab.
Please Follow The Primary Link Above to View the Full Discussion.

Old Unix and Linux 09-08-2009   -   Original Discussion by bhaire
bakunin's Unix or Linux Image
bakunin bakunin is offline Forum Staff  
Bughunter Extraordinaire
Join Date: May 2005
Last Activity: 16 February 2018, 10:45 PM EST
Location: In the leftmost byte of /dev/kmem
Posts: 5,700
Thanks: 112
Thanked 1,642 Times in 1,207 Posts
You are falling for "scripting error number 1": you depend on an environment, which cannot be taken for granted.

Long form: a construct like "./runapp.sh" is telling the shell to execute a program located in the CURRENT directory (the "./" part of the path). This might be the case if you are logged in as your user and manually changed to this directory before. This is NOT the case when cron tries to execute your script, because cron doesn't know that it should manually change into a certain directory first.

Avoid relative paths (everything starting with a "./" in scripts.

Additionally i wonder why the rest of the script worked at all. A command like "ps" is basically an executable and probably located in "/usr/bin/ps". Without a PATH variable pointing to /usr/bin ps shouldn't be found at all. This is also relying on an environment which is probably not set.

In scripts you better set ALWAYS your own environment, because this way you will never encounter problems like these. Here is a sketch of what i mean:

# Example script

# ----------------- global environment
PATH=/usr/bin:/usr/sbin:<and whatever you need>
export PATH
export TERM
# ..... similar for whatever you might also need in your script .....

# -----------------  constants
# ..... similar for whatever you might also need in your script .....

# -----------------  script code itself
m=`ps -ef | grep /install/new/application | wc -l`
if [ $m != 2 ] ; then
     echo "starting application"
     echo "no action taken"

exit 0

Another (minor) observation: if you use ksh do NOT use "echo" for output. There is the built-in "print" command for that, whereas "echo" is an external command.

I hope this helps.

The Following User Says Thank You to bakunin For This Useful Post:
RavinderSingh13 (11-18-2015)