简体   繁体   English

如果 grep 有结果,请发送 email

[英]Send an email if grep has results

I'm trying to do a simple script that if the "grep" comes with results, send the email with the results.我正在尝试做一个简单的脚本,如果“grep”有结果,发送 email 和结果。 But I want also to send an email if there is a case when there are no rejects但如果没有拒绝,我还想发送一个 email

#! /bin/bash

FILE=$(find . /opt/FIXLOGS/l51prdsrv* -iname "TRADX_*.log" -type f -exec grep -F 103=16 {} /dev/null \; )>> Rejects.txt

if [ "$FILE" == true ]
then
    mailx -s "Logs $(date +%d-%m-%y)" "email" < Rejects.txt
    rm -f Rejects.txt
elif [ "$FILE" == null ]
then 
    echo "No Rejects" >> Rejects.txt
    mailx -s "Logs $(date +%d-%m-%y)" "email" < Rejects.txt
    rm -f Rejects.txt
fi

In bash, everything is pretty much just a string.在 bash 中,一切都只是一个字符串。 null is a string, not a null reference like in other languages. null是一个字符串,而不是其他语言中的 null 引用。 true is also a string (unless it's the command true , but that's not the case in your comparison). true也是一个字符串(除非它是命令true ,但在您的比较中并非如此)。

If you want to test that a file exists, you'd use [[ -f "$FILE" ]] .如果你想测试一个文件是否存在,你可以使用[[ -f "$FILE" ]] However, the file is going to exist in your case even if grep matches nothing because bash automatically creates the file when you set it as the destination for your output. What you really need is -s which tests if the file exists and has size greater than 0.但是,即使grep匹配任何文件,该文件也会存在,因为当您将其设置为 output 的目标时,bash 会自动创建该文件。您真正需要的是-s ,它测试文件是否存在并且大小更大小于 0。

#!/bin/bash
find . /opt/FIXLOGS/l51prdsrv* -iname "TRADX_*.log" -type f -exec grep -F 103=16 {} /dev/null \; >> Rejects.txt

if [[ -s Rejects.txt ]] ; then
 : # grep wrote stuff into the file
else
 : # file is empty so grep found nothing
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM