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' --开发者_如何学Python 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?
I would do it with something like
if ! wget ... 2>&1 | grep -q "not retrieving"; then
# run mail command
fi
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)" victim@example.com < /dev/null
else mailx -s "File did not arrive at $(date)" other@example.com < /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)" other@example.com < /dev/null
else mailx -s "File arrived at $(date)" victim@example.com < /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.
if ${WGET_COMMAND_AND_ARGUMENTS} | tail -n 2 | grep -q "not retrieving." ; then
echo "damn!" | mail -s "bad thing happened" user@example.com
fi
精彩评论