3

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.

1
  • 1
    UPWGFBA -- Useless pipe with grep followed by awk :-) Better: MACADDR=$(ifconfig en0 | awk '/ether/ {print $2}') Commented Aug 29, 2011 at 12:24

3 Answers 3

7

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

#!/bin/sh -x

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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:

export PATH=$PATH:/sbin

1 Comment

I do apologize, this was already done in the script without luck. I accidentally omitted it when simplifying the code to post here.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.