Script with curl works manually but not in cron job

12,791

The main difference between running a script on the command line and running it from cron is the environment. If you get different behavior, check if that behavior might be due to environment variables. Cron jobs run with only a few variables set, and those not necessarily to the same value as in a logged-in session (in particular, PATH is often different).

If you want your environment variables to be set, either declare them in ~/.pam_environment (if your system supports it) or add . ~/.profile && at the beginning of the cron job (if you declare them in .profile). See also What's the best distro/shell-agnostic way to set environment variables?

In this case, a 000 status from curl indicates that it could not connect to the server. Usually, the network connection is system-wide, so networking behaves the same in cron. However one thing that's indicated by environment variables is any proxy use. If you need a proxy to connect to the web and you've set the environment variable http_proxy in a session startup script, that setting isn't applied in your cron job, which would explain the failure.

Add the option -S to you curl invocation to display error messages (while retaining -s to hide other messages).

Share:
12,791

Related videos on Youtube

rpayanm
Author by

rpayanm

I love the Free software, Games and Drupal.

Updated on September 18, 2022

Comments

  • rpayanm
    rpayanm almost 2 years

    My script (status.sh) is:

    #!/bin/bash
    SITE=http://www.example.org/
    
    STATUS=$(/usr/bin/curl -s -o /dev/null -I -w "%{http_code}" $SITE)
    
    if [ $STATUS -eq 200 ]
    then
     echo $STATUS >> /home/myuser/mysite-up.log
    else
     echo $STATUS >> /home/myuser/mysite-down.log
    fi
    

    I run:

    $ chmod +x /home/myuser/status.sh
    

    Then on my crontab i got:

    * * * * * /home/myuser/status.sh
    

    When I run:

    $ /home/myuser/status.sh
    

    The file /home/myuser/mysite-up.log contains:

    200
    

    But when cron run, the file /home/myuser/mysite-up.log contains:

    000
    

    What I am doing wrong?

    EDIT: I modified the script adding:

    set -x
    

    as @Sobrique suggested and I the output is:

     SITE=http://www.example.org/
     /usr/bin/curl -s -o /dev/null -I -w '%{http_code}' http://www.example.org/
     STATUS=000
     '[' 000 -eq 200 ']'
     echo 000