Search code examples
bashexecstdoutstdin

Assigning stdin to file also assigns stdout to that file


I executed the following bash script:

#!/bin/env bash
exec 0<log

My understanding is that it permanently reassigns the stdin for this bash process to the log file. So, when I ran

ls > log

I expected that I was passing "ls" to stdin. Since I have not reassigned stdout, I was also expecting to see the result of the "ls" command in the terminal (where I normally see stdout). However, I saw the output of "ls" in the log file. Why is stdout in the log file and not the terminal?


Solution

  • ls writes to whatever file it is given for standard output. Without a redirection, that is whatever file it inherits from its parent (your script). With the redirection, you are explicitly providing the file log for standard output.

    This is independent of whatever else the file log might be used for.