views:

441

answers:

3

I am using wget to grab some files from one of our servers once an hour if they have been updated. I would like the script to e-mail an employee when wget downloads the updated file.

When wget does not retrieve the file, the last bit of text wget outputs is

file.exe' -- not retrieving.
<blank line>

How do I watch for that bit of text and only run my mail command if it does not see that text?

A: 
if ${WGET_COMMAND_AND_ARGUMENTS} | tail -n 2 | grep -q "not retrieving." ; then
    echo "damn!" | mail -s "bad thing happened" [email protected]
fi
Michael Krelin - hacker
You don't need the `${}` (I think you meant `$()` which wouldn't work anyway since it would try to execute the results of the `wget`).
Dennis Williamson
Why then do you think I meant `$()`? Yes, of course I meant `${}`, indeed `{}` is safe to omit, but it doesn't hurt either.
Michael Krelin - hacker
+6  A: 

I would do it with something like

if ! wget ... 2>&1 | grep -q "not retrieving"; then
   # run mail command
fi
jk
Seems simple enough. However, it sends the e-mail no matter what. Even when "not retrieving" is output.Actually, it seems that the output it not being piped into grep for some reason. Looking into it.
Haabda
I'd guess `wget` outputs that "not retrieving" to stderr, not stdout. I edited it to redirect stderr to stdout, so now it should work.
jk
That did it! Thanks jk!
Haabda
+3  A: 

What is the exit status of 'wget' when it succeeds, and when it fails? Most likely, it reports the failure with a non-zero exit status, in which case it is largely trivial:

if wget http://example.com/remote/file ...
then mailx -s "File arrived at $(date)" [email protected] < /dev/null
else mailx -s "File did not arrive at $(date)" [email protected] < /dev/null
fi

If you must analyze the output from 'wget' then you capture it and analyze it:

wget http://example.com/remote/file ... >wget.log 2>&1
x=$(tail -2 wget.log | sed 's/.*file.exe/file.exe/')

if [ "$x" = "file.exe' -- not retrieving." ]
then mailx -s "File did not arrive at $(date)" [email protected] < /dev/null
else mailx -s "File arrived at $(date)" [email protected] < /dev/null
fi

However, I worry in this case that there can be other errors that cause other messages which in turn lead to inaccurate mailing.

Jonathan Leffler