After using `exec 1>file`, how can I stop this redirection of the STDOUT to file and restore the normal operation of STDOUT?

后端 未结 4 1123
灰色年华
灰色年华 2020-12-14 13:04

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 outp

4条回答
  •  一整个雨季
    2020-12-14 13:59

    Q1

    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.

    Q2

    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.

    Q3

    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).

提交回复
热议问题