Patrick Kenny
Patrick Kenny

Reputation: 6397

Bash script with sendmail delivers email when executed manually but not from crontab

I wrote the following bash script to send me an alert if there is a problem with my website:

#!/bin/bash

# 1. download the page
BASE_URL="https://www.example.com/ja"

JS_URL="https://www.example.com/"

# # 2. search the page for the following URL: /sites/default/files/google_tag/google_tag.script.js?[FIVE-CHARACTER STRING WITH LETTERS AND NUMBERS]

curl -k -L ${BASE_URL} 2>/dev/null | grep -Eo "/sites/default/files/google_tag/google_tag.script.js?[^<]+" | while read line
do
    # 3. download the js file
    if curl -k -L ${JS_URL}/$line | grep gtm_preview >/dev/null 2>&1; then
       # 4. check if this js file has the text "gtm_preview" or not; if it does, send an email
       # echo "Error: gtm_preview found"
       sendmail [email protected] < email-gtm-live.txt
    else
      echo "No gtm_preview tag found."
    fi
done

I am running this from an Amazon EC2 Ubuntu instance. When I execute the script manually like ./script.sh, I receive an email in my webmail inbox for example.com.

However, when I configure this script to run via crontab, the mail does not get sent via the Internet; instead, it gets sent to /var/mail on the EC2 instance.

I don't understand why this is happening or what I can do to fix it. Why does sendmail behave different if it is being run from bash vs being run from crontab?

Upvotes: 0

Views: 262

Answers (1)

Mark
Mark

Reputation: 4455

Be aware that the PATH environment variable is different for crontab executions than it is for your typical interactive sessions. Also, not all of the same environment variables are set. Consider specifying the full path for the sendmail executable ( which you can learn by issuing the 'which sendmail' command ).

Upvotes: 1

Related Questions