Linux: stdin, stdout and stderr, how to work with them
bash utilize file descriptors to read and write data, The numerals 0 through 9 are file descriptors .
bash utilize file descriptors to read and write data, The numerals 0 through 9 are file descriptors .
0 stands for standard input: read input to be used from the program
1 stands for standard output: write output from a program
2 stands for standard error: write errors from a program
3 through 9 are spare for any other temporary usage.
By default stdout and stderr print their contents to the terminal screen, stdin uses by default the keyboard unless told not to.
Example: Reading data from stdin
Create file lines.txt with the following contentcat
dog
turtle
Create file my_stdin.sh with the following content
#!/bin/bash
while read line;
do
echo "${line}"
done < /dev/stdinThis script loops the /dev/stdin virtual device for contents until there its no more content to read.
Make it executablechmod +x ./my_stdin.sh
To pass contents of lines.txt to my_stdin.sh we use the < operator<bash_script> < <contents_file>
In our case is./my_stdin.sh < ./lines.txt
cat
dog
turtle
here we have a small problem, how we can separate data coming from a file or a keyboard? we can use the following, save it as my_test.sh#!/bin/bashif [ -t 0 ];
then
echo "Data is coming from keyboard"
else
echo "Data is coming from pipe"
fi
Make it executable and enterecho "test" | ./my_test.sh
Data is coming from pipe./my_stdin.sh < ./lines.txt
Data is coming from pipe./my_test.sh hello
Data is coming from keyboard./my_test.sh
Data is coming from keyboard
In interactive terminals the stdin file descriptor 0 is used by default by the keyboard unless the | or > operators are used, those operators redirect input from keyboard to the files that utilize the operators.
Example: stdout and stderr
As we said before stdout and stderr are used to write useful data and errors to our screen, more than often will be useful to redirect stdout and stderr to a file, the operators to do this are > and >> the main difference between those two operators are that using the > operator is that the file is overwritten while using >> the new data are appended to the end of file.
log contents will be erased a program uses the > operator to write data<program> > log
new log contents will be appended when a program uses the >> operator to write data<program> >> log
This will write only stdout to to log, to write stderr also we use 2>&1 this instructs bash to redirect stdoutto stderr
2>&1if we wish to log stdout and stderr to separate files we use<program> 1>log 2>error
I hope you found this article easy to understand :)