1

I have a bash script where I'm redirecting output into a file for logging.

if test -t 1; then
    # stdout is a terminal
    exec > $OUTPUT_FILE 2>&1
else
    # stdout is not a terminal, no logging.
    false     
fi 

I have one spot later where I actually need output to go to stdout. Is there a way to override just one call to force that?

echo test 1>
1
  • 1
    What about leave as is and tail -f $OUTPUT_FILE ?
    – LatinSuD
    Commented Jun 24, 2014 at 16:23

1 Answer 1

3

You could put this line earlier on in your script:

exec 3>&1

Then whenever you need to send something to go to stdout:

echo "this goes to stdout" 1>&3

Cleanup:

exec 1>&3
echo "now goes to normal stdout"
exec 3>&-  #to remove fd3

How it works is that you define a new file descriptor, 3, and it points to the same place stdout does. You then redirect stdout as needed, but fd3 stays the same as what it was (which is your terminal). When you're done, just remove fd3!

Edit:

If you want output to goto both your file and "classic stdout", do this:

echo "goes both places" | tee -a $OUTPUT_FILE 1>&3

You must log in to answer this question.

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