Haabda
Haabda

Reputation: 1433

Bash scripting: How do I parse the output of a command and perform an action based on that output?

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?

Upvotes: 0

Views: 4949

Answers (3)

JaakkoK
JaakkoK

Reputation: 8387

I would do it with something like

if ! wget ... 2>&1 | grep -q "not retrieving"; then
   # run mail command
fi

Upvotes: 7

Jonathan Leffler
Jonathan Leffler

Reputation: 753525

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.

Upvotes: 3

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143051

if ${WGET_COMMAND_AND_ARGUMENTS} | tail -n 2 | grep -q "not retrieving." ; then
    echo "damn!" | mail -s "bad thing happened" [email protected]
fi

Upvotes: 0

Related Questions