views:

624

answers:

5

I'm looking for a script I can run to check if a text file is empty, if it is then do nothing but if it has something in it, I want it to send me an email with the text file as the message. No idea how to do it.

A: 

Something like this should work.

if [ `wc -l file.txt` -gt 0 ]; then
    mail root@localhost < file.txt
fi
Jack Leow
Interesting, but not very elegant compared with 'test -s' (usually spelled '[ -s ... ]').
Jonathan Leffler
However, if you change wc -l to wc -w, then the file will not be emailed if it just contains whitespace, which could be nice.
Michael Mior
Yeah, I should have gone with `test -s`. It's been a while since I've written shell scripts.
Jack Leow
+1  A: 

As a script

#!/bin/bash
file=file_to_check
if [ -s ${file} ] ; then
  mail -s "The file is not empty!" [email protected] < $file
fi

Or in one line. (To put in a crontab)

   [ -s file_to_check ] && mail -s 'File is not empty' [email protected] < file_to_check
jabbie
PERFECT!I'll put it at the end of the script that generates the file so I wont need to estimate when the file will be there... just i just need it to send from a different email address lol but i'll read the man pages on mail and figure it out.
Hintswen
The '-z' test checks whether the string (file name) is zero length, not whether the file is zero length.
Jonathan Leffler
so it does... onto the next answer rofl >.<
Hintswen
@Hintswen yep, it should be '-s' I should have manned test. That is what I get when I try to answer a question right before. Bed.
jabbie
+4  A: 

For example:

test -s your_file && mutt -a your_file -s "Sending you a file" [email protected]

This will send the file as attachment. If you want to include the file in the message body, you can use the -i switch instead of the -a. If you don’t have Mutt installed you can call mail:

test -s your_file && mail -s "Sending you a file" [email protected] < your_file
zoul
:S ./mail: line 1: mutt: command not found
Hintswen
copied it again, dunno what was wrong the first time... no errors but it doesn't send me anything :(
Hintswen
A: 

For sending email using bash check the following link http://rzdesign.free.fr/?p=26

Geos
+2  A: 
[ -s "$f" ] && mail [email protected] -s "$f contents" < $f

Nice and compact :)

Leigh Gordon