Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Once STDERR is redirected, for example to a file, how can it be redirected back to the original file descriptor 2?

#!/bin/sh
exec 2>/tmp/err
print -u2 'log errors to file'
exec 2>&2  (how do we do this???)
print -u2 'log errors to console'

Context

This redirection solution should work in a cron job. For example, if cron executes an external script, that script will redirect stdout and stderr to relevant log and error files, respectively. However, if an execution in the script fails or something needs to be reported to the job owner, I need to output the error messages so cron will receive them and send mail.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

Try:

#!/usr/bin/env ksh
exec 2>ksh_err.txt
print -u2 'log errors to file'
exec 2>`tty`
print -u2 'log errors to console'

Edit 1:

#!/usr/bin/env ksh

exec 8>err.txt
print -u8 'log errors to file'
print -u2 'log errors to console'

Edit 2:

#!/usr/bin/env ksh

exec 3>&2
exec 2>err.txt
print -u2 'log errors to file'
exec 2>&3
print -u2 'log errors to console'
share|improve this answer
    
This would work if my situation was different. I just updated my question. –  Clint Pachl Oct 4 '10 at 7:08
    
I've updated my answer. –  Casual Coder Oct 4 '10 at 8:20
    
That would work too, but just not in my case because I cannot control which file descriptor gets written to. The script in question running from cron contains dump(8). Dump by default writes status/progress to STDERR and dump data to STDOUT (pipe to SSH). I want to redirect dump's STDERR to a dumplog for the entire script because there are several invocations of dump throughout the script. However, if the script must report other errors, I would like to do a re-redirect back to the original STDERR on file descriptor 2. Hope that makes sense. –  Clint Pachl Oct 4 '10 at 9:31
    
Answer updated. –  Casual Coder Oct 4 '10 at 10:05
    
Third times a charm! You get a cookie for that Casual Coder! I haven't seen this trick for many years and completely forgot it. That's it though, basically save a pointer to the original descriptor before it's overwritten. Cool. –  Clint Pachl Oct 4 '10 at 11:26
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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