English 中文(简体)
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?

最佳回答

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




相关问题
What does it mean "to write a web service"?

I just asked a question about whether it was possible to write a web-page-checking code and run it from free web server, and one supporter answered and said that it was possible only if I run "a web ...

How can I use exit codes to run shell scripts sequentially?

Since cruise control is full of bugs that have wasted my entire week, I have decided the existing shell scripts I have are simpler and thus better. Here is what I have so far svn update /var/www/...

Dynamically building a command in bash

I am construcing a command in bash dynamically. This works fine: COMMAND="java myclass" ${COMMAND} Now I want to dynamically construct a command that redirectes the output: LOG=">> myfile.log ...

Why does Scala create a ~/tmp directory when I run a script?

When I execute a Scala script from the command line, a directory named "tmp" is created in my home directory. It is always empty, so I simply deleted it without any apparent problem. Of course, when I ...

Ivy, ant and start scripts

I have a project that uses ant to build and ivy for dependencies. I would like to generate the start scripts for my project, with the classpath, based on the dependencies configured in Ivy, ...

热门标签