Restoring stdout and stderr to default values

In the shell script, we can change the default input to the file using the exec command, as shown below:

exec 1>outputfile 

However, if in the same script, if I want to restore the stdout '1' descriptor to the default (terminal). How can we achieve this?

+6
source share
2 answers

In this example

 Example 20-2. Redirecting stdout using exec #!/bin/bash # reassign-stdout.sh LOGFILE=logfile.txt exec 6>&1 # Link file descriptor #6 with stdout. # Saves stdout. exec > $LOGFILE # stdout replaced with file "logfile.txt". # ----------------------------------------------------------- # # All output from commands in this block sent to file $LOGFILE. echo -n "Logfile: " date echo "-------------------------------------" echo echo "Output of \"ls -al\" command" echo ls -al echo; echo echo "Output of \"df\" command" echo df # ----------------------------------------------------------- # exec 1>&6 6>&- # Restore stdout and close file descriptor #6. echo echo "== stdout now restored to default == " echo ls -al echo exit 0 

Appears to show what you want. He came from here , where there is a little discussion and other relevant information.

+5
source

Try the tee command:

 exec | tee outputfile 

Take a look at the tee man page for more explanation:

tee - read from standard input and write to standard output and files

0
source

All Articles