I am trying to execute the following:
exec &>filename
After this I am not able to see anything including what I typed, alright.
I frantically try , exec 1>&1 and exec 2>&2 , but nothing happens.
Now , without killing the shell , how do I get back the output redirected to the stdout and error redirected to stderr respectively?
Are the file descriptors the only way to refer standard [in|out]put and stderr?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
After you run exec &>filename, the standard output and standard error of the shell go to filename. Standard input is file descriptor 0 by definition, and standard output is fd 1 and standard error is fd 2.
A file descriptor isn’t either redirected or non-redirected: it always go somewhere (assuming that the process has this descriptor open). To redirect a file descriptor means to change where it goes. When you ran exec &>filename, stdout and stderr were formerly connected to the terminal, and became connected to filename.
There is always a way to refer to the current terminal: /dev/tty. When a process opens this file, it always means the process’s controlling terminal, whichever it is. So if you want to get back that shell’s original stdout and stderr, you can do it because the file they were connected to is still around.
exec &>/dev/tty
Method 2
You want
exec &>$(tty)
What you’re doing in your question is replicating in stdout and stderr the original stdout and stderr which have already been redirected to the file.
As Gilles’ answer explains, tty will return the terminal device of the current terminal. This is where the three standard file descriptors are coming from/going to by default in a login shell. So the above statement makes use of tty to redirect stdout and stderr back to the terminal device as they were before.
If you’re concerned about portability (as per your comment on Gilles’ answer), both methods (the tty utility and the /dev/tty file) are in the POSIX standard.
Copied verbatim from Gilles’ comment:
There's an advantage to /dev/tty: it works even after exec <somefile, whereas $(tty) would complain “not a tty”
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0