2

I'm trying to redirect all commands error output to a file like that:

exec 2>errlog.txt

but executing the line above leaves me with a "frozen" terminal - the terminal doesn't respond to my input at all. What's more interesting redirecting stdout using exec works great. What's wrong with error redirection?

Daros
  • 21

1 Answers1

5
exec 2>errlog.txt

If you're using bash (and not ksh93 or dash [1]), that will not freeze your terminal. That will only prevent the shells's prompts and the characters you enter from being echoed back.

But you will able to retrieve them later from errlog.txt ;-) You can easily check that by blindly typing pwd<Enter> or ls<Enter>: the commands will work fine and display their output. Also, ^C and ^Z will work as expected.

There are two things at work here:

1) bash is always printing its prompt to stderr, not to the controlling terminal.

2) the readline library bash is using to implement command line editing will turn off the echo flag on the terminal [2], and print itself the characters entered by the user to stderr.

If you start a bash shell with bash --noediting (which will cause it to not use the readline library), the characters you enter will be echoed back by the tty driver, and only the prompts will go to the redirected stderr.

A workaround for this may be to use tee and a process substitution:

exec 2> >(trap '' INT; tee errlog.txt >/dev/tty)

[1] see here for an explanation why some shells will badly misfunction if you do that, and why that will work as expected in zsh.

[2] see the c_lflag / ECHO in the termios(3) manpage and stty echo in stty(1) for a description.