1

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.

1 Answer 1

2

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'
5
  • This would work if my situation was different. I just updated my question. Oct 4, 2010 at 7:08
  • I've updated my answer. Oct 4, 2010 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. Oct 4, 2010 at 9:31
  • Answer updated. Oct 4, 2010 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. Oct 4, 2010 at 11:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .