Reputation: 113
I'm trying to run a scheduled cron job and email the output to a few users. However, I only want to e-mail the users if something new happened.
Essentially, this is what happens:
I run a python script, it then checks the filename on an FTP server. If the filename is different, it then downloads the file and starts parsing the information. The filename of the previously downloaded file is stored in last.txt - and if it does, indeed, find a new file then it just updates the filename in last.txt
If the filename is the same, it stops processing and just outputs the file is the same.
Essentially, my thoughts were I could do something similar to:
cp last.txt temp.last.txt | python script.py --verbose > report.txt | diff last.txt temp.last.txt
That's where I got stuck, though. Essentially I want to diff the two files, and if they're the same - nothing happens. If they differ, though, I can e-mail the contents of report.txt to a couple of e-mail address via mail command.
Hopefully I was detailed enough, thanks in advance!
Upvotes: 1
Views: 1111
Reputation: 351
First of all, no need for the pipes |
in your code, you should issue each command separately.
Either separate them by semicolon or write them on separate lines of the script.
For the problem itself, one solution would be to redirect the output of diff to a report file like:
cp last.txt temp.last.txt
python script.py --verbose > report.txt
diff last.txt temp.last.txt > diffreport.txt
You can then check if the report file is empty or not as described here: http://www.cyberciti.biz/faq/linux-unix-script-check-if-file-empty-or-not/
Based on the result, you can send diffreport.txt and report.txt or just delete all of it.
Here is a quick example for how your cron job script should look like:
#!/bin/bash
# Run the python script
cp last.txt temp.last.txt
python script.py --verbose > report.txt
diff last.txt temp.last.txt > diffreport.txt
# Check if file is empty or not
if [ -s "diffreport.txt" ]
then
# file is not empty, send a mail with the attachment
# May be call another script that will take care of this task.
else
# file is empty, clean up everything
rm diffreport.txt report.txt temp.last.txt
fi
Upvotes: 2