So what are stdin, stdout, and stderr in Linux or Unix bash?
The longer I live, the more I realize that I am never wrong about anything, and that all the pains I have so humbly taken to verify my notions have only wasted my time!
Whenever we run a command in the terminal, the terminal creates three data streams one for standard input, one for standard output, and one for standard error.
STDIN: As said previously stdin is responsible for taking input in the terminal. We use the read command to take user input from the keyboard. This read command is using stdin stream.
read
STDOUT: When we run a command in the terminal, the output(not error output) is sent to the stdout, and the terminal prints it.
ls -la
STDERR: STDERR is the stream where the error from a command is sent.
acommand
In Linux, all the streams are taken as virtual files and like real files, we can read from them or write in them. And to uniquely identify each of these virtual files a file descriptor number is assigned to each. The file descriptor for these three streams are given below:
- STDIN -> 0
- STDOUT -> 1
- STDERR -> 2
So how can we read from these streams specifically? For example, if we want to run a command and read from the maybe, stderr stream, and stdout stream separately.
We have discussed the file descriptor of these streams already.
If we want to write in a file from the stderr stream we simply use this command
anything 2> err.txt
we can also read from multiple streams and write to numerous file.
anything 2> err.txt 1> output.txt