Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restoring stdout and stderr to default value

In shell script, We can change the default input to a File using the exec command as follow :

  exec 1>outputfile

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

like image 916
Naved Alam Avatar asked Jan 14 '14 05:01

Naved Alam


People also ask

What is the meaning of 2 >& 1?

The 1 denotes standard output (stdout). The 2 denotes standard error (stderr). So 2>&1 says to send standard error to where ever standard output is being redirected as well.

Can you redirect stdout and stderr to the same file?

When saving the program's output to a file, it is quite common to redirect stderr to stdout so that you can have everything in a single file. > file redirect the stdout to file , and 2>&1 redirect the stderr to the current location of stdout . The order of redirection is important.

Where does stderr go by default?

By default, stderr is typically connected to the same place as stdout, i.e. the current terminal.


Video Answer


1 Answers

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. It came from the ABS, where there is a small amount of discussion and other relevant information.

like image 87
GreenAsJade Avatar answered Oct 25 '22 15:10

GreenAsJade