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

后端 未结 4 1124
灰色年华
灰色年华 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 14:01

    Q1: There is a simple way to restore stdout to the terminal after it has been redirected to a file:

    exec >/dev/tty
    

    While saving the original stdout file descriptor is commonly required for it to be restored later, in this particular case, you want stdout to be /dev/tty so there is no need to do more.

    $ date
    Mon Aug 25 10:06:46 CEST 2014
    $ exec > /tmp/foo
    $ date
    $ exec > /dev/tty
    $ date
    Mon Aug 25 10:07:24 CEST 2014
    $ ls -l /tmp/foo
    -rw-r--r-- 1 jlliagre jlliagre 30 Aug 25 10:07 /tmp/foo
    $ cat /tmp/foo
    Mon Aug 25 10:07:05 CEST 2014
    

    Q2: exec 1>file is a slightly more verbose way of doing exec >file which, as already stated, redirect stdout to the given file, provided you have the right to create/write it. The file is created if it doesn't exist, it is truncated if it does.

    exec 1>&- is closing stdout, which is probably a bad idea in most situations.

    Q3: The commands should be

    exec 0<&-
    exec 1>&-
    exec 2>&-
    

    Note the reversed redirection for stdin.

    It might be simplified that way:

    exec <&- >&- 2>&-
    

    This command closes all three standard file descriptors. This is a very bad idea. Should you want a script to be disconnected from these channels, I would suggest this more robust approach:

    exec /dev/null 2>&1
    

    In that case, all output will be discarded instead of triggering an error, and all input will return just nothing instead of failing.

提交回复
热议问题