Reputation: 89
We can use EXEC command to redirect all the STDOUT and STDERR to a .log file, like:
#!/bin/bash
exec 1> record.log 2>&1
echo begin redirecting
# from the script above, 'begin redirecting' will be redirected to record.log
# then we want to disable the redirecting and restore the STDOUT&STDERR
echo return to STDOUT and STDERR
# here 'return to STDOUT and STDERR' will be print out
Does any one knows how to disable the redirecting(both STDOUT and STDERR)? In this way, we can just redirect part of the output to a file by using exec command. Thank you so much.
Upvotes: 0
Views: 248
Reputation: 397
Why not limit the scope of the redirection with a sub-shell? E.g.
#!/bin/bash
(
exec 1> record.log 2>&1
echo begin redirecting
)
echo This goes to stdout
You might have issues if you set variables in the inner scope though. Depends how your program is structured.
Upvotes: 0
Reputation: 785641
You can do:
#!/bin/bash
# Link file descriptor #6 with stdout/stderr
exec 6>&1 2>&1
exec 1> record.log 2>&1
echo begin redirecting
# restore and close file descriptor #6
exec 1>&6 2>&1 6>&-
# from the script above, 'begin redirecting' will be redirected to record.log
# then we want to disable the redirecting and restore the STDOUT&STDERR
echo return to STDOUT and STDERR
Upvotes: 1