Bash – Why does bash interactive shell by default write its prompt and echoes its interactive input to stderr

bashpromptstderr

I just noticed that bash interactive shell by default writes the prompt and echoes anything you type to file descriptor 2 (stderr). This can be verified by running bash inside strace.

What is the reason for this? Why does it not write these things to stdout?

Best Answer

The original UNIX versions 5-7 can be seen doing the same thing. (UFD output = 2; http://minnie.tuhs.org/cgi-bin/utree.pl?file=V7/usr/src/cmd/sh/main‌​.c)

time is/was a builtin, and it's definitely useful that it outputs to stderr. However time is not one of the builtins in V5.

I don't think there were any big reasons not to write terminal output to stderr. Output from the shell was either clearly an error message, or output intended for interactive terminals only. It was not necessary for redirecting stdout to redirect the interactive output.

Although stderr was introduced in V6, not V5, in V5 sh manually dup()s stdout to FD 2 after closing the old FD 2 if necessary. It seems they already found a need to print error messages e.g. if exec() failed when trying to launch a command like foo > output.

Now pay attention to how compact the historical unix code is. It is deliberately kept short, because there wasn't necessarily very much physical RAM.

There is a single prs() function to print strings. It does not take an FD parameter. It prints error messages to FD 2, and the other strings are also OK to print to FD 2, so it simply prints to FD 2 unconditionally. Short code, that compiles to few instructions, hence using minimal RAM.

And once things are around for a while, changing them always has the risk of breaking more things than it improves.

What puzzles me is why the developers of python even noticed this and copied it - IMO it's a pretty obscure fact. Maybe it implies an additional reason that I haven't found.

err(s)
char *s;
{

    prs(s);
    prs("\n");
    if(promp == 0) {
        seek(0, 0, 2);
        exit();
    }
}

prs(as)
char *as;
{
    register char *s;

    s = as;
    while(*s)
        putc(*s++);
}

putc(c)
{

    write(2, &c, 1);
}
Related Question