I have a script that updates a server with some stats once per day. The script works as intended when running from command line, but when running from cron some of the variables are not passed to curl.
Here is an example of the code:
#!/bin/sh
PATH=/bin:/sbin:/usr/bin:/usr/sbin
/bin/sh /etc/profile
MACADDR=$(ifconfig en0 | grep ether | awk '{print $2}')
DISKUSED=$(df / | awk '{print $3}' | tail -n1)
DISKSIZE=$(df / | awk '{print $2}' | tail -n1)
# HTTP GET PARAMS
GET_DELIM="&"
GET_MAC="macaddr"
GET_DS="disk_size"
GET_DU="disk_used"
# Put together the query
QUERY1=$GET_MAC=$MACADDR$GET_DELIM$GET_DS=$DISKSIZE$GET_DELIM$GET_DU=$DISK_USED
curl http://192.168.100.150/status.php?$QUERY1
The result in the cron job is http://192.168.100.150/status.php?macaddr=&disk_size=&disk_used=
I am not sure if it is some problem with the variables, or possibly with awk trying to parse data with no terminal size specified, etc.
Any help is appreciated.
One problem I've run into with crons is that variables you take for granted do not exist. The main one you take for granted is the path variable.
Echo what you have set as your path when being run from the command line and put that in the top of your script (or in the top of the crontab).
Alternatively, specify the full path to each command - ifconfig, awk, grep, etc.
I would guess that will fix the problem.
Very first command in your script
ifconfig
is found in/sbin/ifconfig
on Mac. And the default PATH variable for cron jobs is set to:/usr/bin:/bin
That's the reason probably rest of your commands are also failing.It is better to set the PATH manually at the top of your script. Something like:
When you're running into problems like this it's almost always an environment issue.
Dump the results of "env" to a file and inspect that. You can also run your script with top line of
to see what's happening to all the variables. You might want to use a wrapper script so you can redirect the output this provides for analysis.