Reputation: 764
I am working with a shell script to run my analyses. To make sure, I can confirm the correct commands were executed, I am writing the complete STDOUT/STDERR output into a file
My script looks like that:
#!/bin/bash
# Here are some pliminary stuff
echo " this goes still to the STDOUT to control the begining of the script"
#### execute all output to log files
# to set a log file, where all echo command will be redirected into.
touch $projectName\_logfile.txt # creating the log file
exec &> $projectName\_logfile.txt # direct all output to the log file
echo "1. These steps should be written to the log file"
# exit
# exec >&-
echo "2. 2. these steps should be written to the STDOUT again!"
# The script should be able to continue here ...
As you can see I have tried both using the exit
command as well as closing the file descriptor using exec
again. But both have failed.
I would appreciate your help to understand how to close the connection to the log file and redirect everything back to the STDOUT/STDERR.
thanks Assa
Upvotes: 2
Views: 2520
Reputation: 1383
I would rather consider this way:
echo "to out 1"
{
echo "to log 1"
echo "to log 2"
} &> ./_logfile.txt
echo "to out 2"
Anyway if You still need to use Your approach then You need to save original file descriptors:
exec 3<&1 # save original stdout to 3
exec 4<&2 # save original stderr to 4
And then restore:
exec 1>&3 # restore original stdout
exec 2>&4 # restore original stderr
Your example:
#!/bin/env bash
echo " this goes still to the STDOUT to control the begining of the script"
touch ./_logfile.txt # touch the log file
exec 3<&1 # save original stdout to 3
exec 4<&2 # save original stderr to 4
exec &> ./_logfile.txt # direct all out and err to the log file
echo "1. These steps should be written to the log file"
exec 1>&3 # restore original stdout
exec 2>&4 # restore original stderr
echo "2. 2. these steps should be written to the STDOUT again!"
# The script should be able to continue here ...
Upvotes: 3