bash pipe to log and stderr

Posted on 2005-04-24
Last Modified: 2008-01-09
I have a bash script that runs and outputs its logging info to $LOGDIR/$LOGFILE. However, if I run it from cron, I want stderr to be sent both to the log file and also to stderr so that I'll get emailed about the problem.

To put it another way, if I output to the log file by doing
  doFooStuff >> $LOGDIR/$LOGFILE
then it'll output stdout to the log file and stderr to cron email that I'll get.

If I do:
  doFooStuff >& $LOGDIR/$LOGFILE
then it'll output both stdout and stderr to the log file, but I'll never get any cron email.

What can I do? I can't grep the log for error messages because there's no guaranteed string that will indicate an error.

I know that "tee" could somehow be used for stdout. But, I don't want stdout sent in the cron emails. I only want stderr.
Question by:HappyEngineer
    LVL 23

    Expert Comment

    command_here   2>&1 1<&- 1>/dev/null | tee -a logfile 1>&2

    Basically, this involves   moving stderr to stdout, closing descriptor 1,
    re-opening  descriptor 1 to /dev/null,  calling tee, and
    duplicating stdout back to stderr.
    LVL 38

    Accepted Solution

    Say, your is called Use another script to wrap it, say
    --- ---

    LOGFILE=<log file name>_`date +%m%d%Y`

    /  > $LOGDIR/$LOGFILE  2>&1
    mail -s "log file"  <your email address>  < $LOGDIR/$LOGFILE  
    For redirection, the syntax is read from "right-to-left", it the syntax is
    /  > $LOGDIR/$LOGFILE  2>&1
    where 2>&1 will be read first and it tells that stdout plus stderr will redirect to $LOGDIR/$LOGFILE.

    In cron job,
    * * * * * / > /dev/null 2>&1
    since your log file is sent inside the No need to send through cron daemon.
    This way you can control the emails being sent to whom.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    I. Introduction There's an interesting discussion going on now in an Experts Exchange Group — Attachments with no extension ( This reminded me of questions tha…
    The purpose of this article is to demonstrate how we can use conditional statements using Python.
    Connecting to an Amazon Linux EC2 Instance from Windows Using PuTTY.
    Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now