LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   [bash] redirect all subsequent std output to file (https://www.linuxquestions.org/questions/programming-9/%5Bbash%5D-redirect-all-subsequent-std-output-to-file-788509/)

hashbang#! 02-11-2010 02:18 PM

[bash] redirect all subsequent std output to file
 
I have got a script with an outer and inner loop. The inner loop issues loads of echo's which need to be redirected to a log file determined by the outer loop.

The obvious solution is to redirect every echo to >$LOG and set LOG in the outer loop.

Code:

for f in $FILES ; do
    LOG=<logfile>
    for l in $LINES ; do
        ...
        echo blah >$LOG
        ...
        echo blah >$LOG
    done
done

I was just wondering whether it is possible to map stdout to $LOG in the outer loop without having to redirect every subsequent individual command output?

rweaver 02-11-2010 02:34 PM

If memory serves me you want to do something like this:

Code:

# redirect stdout to file descriptor
exec 6>&1
# redirect it to logfile
exec > /path/to/your/log/file.log

# your loop
(LOOP)

# fix your stdout and close file
exec 1>&6 6>&-

Actually, I found where my snippet came from as I was looking into this to make sure it was right (I lost a shell or two doing this with stdin.)

http://www.linuxtopia.org/online_boo...ripting_guide/

Check out chapter 16 "I/O Redirection", sub chapter 16.1 "Using exec". That has better details and more in-depth instruction than I can provide from memory.

Edit: I'd also suggest redirecting stderr or you might miss some messages from applications in your loop

tuxdev 02-11-2010 02:54 PM

Code:

for file in "${files[@]}" ; do
    log=<logfile>
    for line in "${lines[@]}" ; do
        ...
        echo blah
        ...
        echo blah
    done >> "$log"
done


hashbang#! 02-11-2010 04:20 PM

An answer to something I didn't think there was an answer to in under fifteen minutes - amazing!

How can you redirect stderr to the same file as stdout using the exec method?

hashbang#! 02-11-2010 05:01 PM

Note:
Code:

exec 6>&1
exec >file.log

overwrites an existing file.log
Code:

exec 6>&1
exec >>file.log

redirects and appends to file.log


All times are GMT -5. The time now is 06:31 AM.