automated, shell

Quiet grep

Usually during an cron job, one needs to check for an expression in a log file, or in the output of a command, without generating any cumbersone new output (such as a standard grep would do): this is exactly the use of the -q option of grep. For example:

for i in `grep -v '^#' /etc/passwd | cut -f1 -d:`
    grep $i /var/log/samba/log.smbd | grep -q 'failed to authenticate'
    if [ $? == 0 ] ; then
        mail -s 'Error in samba' $i <<EOM
        You failed to authenticate at least once. Please be more careful...

The above script will send a short notice to any user whose samba session produced a “failed to authenticate” message. Obviously, the log.smbd file should be rotated frequently (at least as much as the script’s frequence).

Strictly speaking, man grep specifies that neither the -q nor the -s options should be used if compatibility with old versions of grep is desired… One should redirect all output to /dev/null, but we have already spoken about this, and it is likely that you do not need that compatibility in your new home-made scripts.

speak up

Add your comment below, or trackback from your own site.

Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*Required Fields