2

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

Assa Yeroslaviz
  • 590
  • 1
  • 9
  • 22

1 Answers1

3

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 ...
Kubator
  • 1,373
  • 4
  • 13
  • thanks a lot for the answer. this works well. I would still use my script, as there are multiple functions and different tools, all creating output and I think it looks cleaner, when there is only one command to redirect the output to a file. Is there a specific reason, why this method is not good? thanks – Assa Yeroslaviz Apr 11 '19 at 08:03
  • Glad that helped. Sure thing if Your method looks cleaner for Your case then use it. What I can think of using exec way is that You have to be more pedantic in code. You can also create functions of redirect/restore if You need to use multiple times. – Kubator Apr 11 '19 at 08:20