redirection of stdout & stderr

I've been trying to redirect output of errors from a script job (through cron) to mailx. This works fine, but I loose the stderr going out to the logfile. Ideally I'd like to get stderr & stdout to a log file AND stderr on it's own to mailx.
/tmp/test > /tmp/test.log 2 > 'mailx root'

I've been playing with variations of using "tee" to output to two destinations, but no joy...
I've also tried to manipulate file descriptors but still no joy...
/tmp/test > /tmp/test.log 3>&2 2>&1 3 > 'mailx root'

am I going in the right direction or lost altogether ?
Who is Participating?

Improve company productivity with a Business Account.Sign Up

ahoffmannConnect With a Mentor Commented:
(script > logfile) 2>&1|tee -a logfile|mailx root
/tmp/test 2>&1 >/tmp/test.log | mailx root
ferguswilsonAuthor Commented:
your suggestion is doing the same thing
it just directs the errors FROM the logfile TO mailx
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

If you don't mind using a tempfile, maybe ...

  (/tmp/test 2>&1 1>&3 | tee /tmp/test.err) > /tmp/test.log 3>&1 ; test -z /tmp/test.err || mailx root < /tmp/test.err

ferguswilsonAuthor Commented:
not really, temp files wouldn't really be a good idea. If I was to go down the road of extra files, I'd be taking a different route than this.
Basically you can:

  1.redirect stdout to a file
  2.redirect stderr to a file
  3.redirect stdout to a stderr
  4.redirect stderr to a stdout
  5.redirect stderr and stdout to a file
  6.redirect stderr and stdout to stdout
  7.redirect stderr and stdout to stderr

Consider this:
exec 3>&1; script 2>&1 1>&3 3>&- | mailx root 1>&2 3>&-

Normal output would be unaffected. The closes there were in case something really cared about all its FDs. We send stderr to sed, and then put it back out 2.

Or did I misunderstood the original question ? ;)
ferguswilsonAuthor Commented:
this done the trick for me, thanks.
for the record though, it sent an email even if there wern't any errors going to stderr;
Your "cron" job
(/sys/test > /sys/test.log) 2>&1|tee /sys/test.log|mailx root
 produced the following output:
UX:mailx: WARNING: No message !?!  Message not sent

...but putting in || at the end resolved it
(/sys/test > /sys/test.log) 2>&1|tee /sys/test.log||mailx root

thanks for your help,
aah, nice trick: ||
You got used to shells ;-)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.