2009-12-31 62 views
0

我正在使用wget从一台服务器上抓取一些文件,一小时一次,如果它们已经更新。我希望脚本在wget下载更新的文件时通过电子邮件向员工发送电子邮件。Bash脚本编写:如何解析命令的输出并根据该输出执行操作?

当wget的不检索文件,文本wget的输出的最后一位是

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

我怎么看文本的该位,只运行我的邮件命令,如果它没有看到文本?

回答

7

我会像

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

似乎很简单。但是,无论发生什么,它都会发送电子邮件。即使输出“不取回”。 实际上,出于某种原因,它似乎没有将输出传送到grep。看着它。 – Haabda 2009-12-31 23:17:19

+0

我猜'wget'输出“不检索”到标准错误,而不是标准输出。我编辑它将stderr重定向到stdout,所以现在它应该工作。 – JaakkoK 2009-12-31 23:23:32

+0

这样做!谢谢jk! – Haabda 2009-12-31 23:25:52

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

你不需要'$ {}'(我认为你的意思是'$()',因为它会尝试执行'wget'的结果,所以它不会工作。 – 2009-12-31 23:53:39

+0

为什么你觉得我的意思是'$()'?是的,当然我的意思是'$ {}',事实上'{}'可以省略,但它也不会伤害。 – 2010-01-01 14:45:14

3

什么是“wget”退出状态时,它成功做到这一点,当它失败了呢?最有可能的,它会报告有一个非零退出状态的失败,在这种情况下,它在很大程度上是微不足道的:

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 

如果你必须分析从“wget”那么你抓住它,分析它的输出:

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 

但是,我担心在这种情况下,可能会有其他错误导致其他邮件导致邮件不准确。