I am trying to record each mail sent to my local inbox from the cron job in to another txt file. When I use the line

mail | grep cron > cron_mail.txt

the operation does not stop and creates an empty cron_mail.txt.

How would I fix this, or is there an easier way to complete this operation in bash?

  • Why do you need it, maybe you only want to turn log file for cron? – Krzysztof Stasiak Jun 9 '17 at 7:48
  • That sounds like it would work better, could you direct me to any good resources for that operation? – thenewbie Jun 9 '17 at 10:07
  • what distro you have? default logs is sended to syslog, you can redirect it to cron.log in rsyslog.d (uncoment line with cron in /etc/rsyslog.d/50-default.conf) – Krzysztof Stasiak Jun 9 '17 at 10:29

It seems that mail outputs to the standard error stream, so that it doesn't get piped to grep, as only standard output is piped.

Try mail 2>&1 | grep cron > cron_mail.txt

2 is the file descriptor of the standard error stream, and with the command above, it will get redirected to standard output, which in turn gets piped.

| improve this answer | |

If your local mail spool is a Berkeley mailbox file, try

grep '^From cron  ' "$MAIL"

This relies on the fact that Berkeley mbox files use a line starting with From, the sender's envelope address, and two spaces (usually followed by the message's arrival time) as the separator line fefore each new message. (A consequence of this is that the message body cannot contain the five characters From at beginning of line anywhere in it.) If your cron daemon's messages contain e.g. a FQDN domain name, you'll obviously need to adapt the regex.

Berkeley mbox used to be ubiquitous, but these days, many systems use other mailbox formats, many of which are folder-based, rather than a single flat file. For maildir, a common format especially for IMAP mailboxes, try

find new cur tmp -type f -exec grep -m 1 '^From:' /dev/null | grep cron

which examines the From: header in each message (this is distinct from the similarly labelled Berkeley separator line, which isn't a mail header at all). You'd run this in the folder you want to examine, or include the full path to the new, cur, and tmp subdirectories in the directory arguments.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.