I am a newbie in shell scripting and I am using Ubuntu-11.10. In the terminal after using exec 1>file
command, whatever commands I give to terminal, its output doesn't get shown in terminal. I know that STDOUT is getting redirected to the file, the output of those commands gets redirected to file.
My questions are here
Once I use exec 1>file
, how can I get rid of this? i.e. How can I stop the redirection of STDOUT to file and restore the normal operation of STDOUT (i.e. redirection to terminal rather than file)?
I tried using exec 1>&-
but it didn’t work as this closes the STDOUT file descriptor.
Please throw light on this entire operation of exec 1>file
and exec 1>&-
What will happen if we close the standard file descriptors 0, 1, 2 by using exec 0>&-
exec 1>&-
exec 2>&-
?
You have to prepare for the recovery before you do the initial exec
:
exec 3>&1 1>file
To recover the original standard output later:
exec 1>&3 3>&-
The first exec
copies the original file descriptor 1 (standard output) to file descriptor 3, then redirects standard output to the named file. The second exec
copies file descriptor 3 to standard output again, and then closes file descriptor 3.
This is a bit open ended. It can be described at a C code level or at the shell command line level.
exec 1>file
simply redirects the standard output (1) of the shell to the named file. File descriptor one now references the named file; any output written to standard output will go to the file. (Note that prompts in an interactive shell are written to standard error, not standard output.)
exec 1>&-
simply closes the standard output of the shell. Now there is no open file for standard output. Programs may get upset if they are run with no standard output.
If you close all three of standard input, standard output and standard error, an interactive shell will exit as you close standard input (because it will get EOF when it reads the next command). A shell script will continue running, but programs that it runs may get upset because they're guaranteed 3 open file channels — standard input, standard output, standard error — and when your shell runs them, if there is no other I/O redirection, then they do not get the file channels they were promised and all hell may break loose (and the only way you'll know is that the exit status of the command will probably not be zero — success).