sander
sander

Reputation: 141

Email the output of a shell script

I have a shell script (script.sh) in which I run a simple python web scraper

python3 script.py

As I run this shell script in a cron job, I want to be notified by email if something goes wrong. I found this code on stackoverflow, which I put at the bottom of my .sh script:

./script.sh 2>&1 | tee output.txt | mail -s "Script log" [email protected]

The problem is that the script now seems to be looping; where it should only take a few seconds, it now takes a few minutes to run and I receive 10-20 emails in my mailbox. The content of these emails differs, most of the times the emails are empty, but sometimes they contain messages such as:

./script.sh: 4: ./script.sh: Cannot fork 

or:

mail: Null message body; hope that's ok 

I'm not sure what goes wrong here. What can I do to fix this?

Upvotes: 0

Views: 1365

Answers (1)

Mike Guelfi
Mike Guelfi

Reputation: 132

The script runs, runs the python, then calls itself again, until it runs out of resources and fails to fork.

The .sh should contain:

python3 script.py 2>&1 | tee output.txt | mail -s "Script log" [email protected]

Assuming you actually want to create output.txt in whatever folder pwd is... otherwise you could leave that out entirely.

Alternatively you could just configure your MAILTO in your crontab (see https://www.cyberciti.biz/faq/linux-unix-crontab-change-mailto-settings/)

Upvotes: 1

Related Questions