File descriptors are integers associated with file input and output. They keep track of open files. The most well-known file descriptors are stdin, stdout, and stderr. We can even redirect the contents of a file descriptor to another descriptor.
When writing scripts, stdin, stdout, and stderr are often used. Redirecting an output to a file by filtering the content is a basic thing we need to do.
A file descriptor is an integer value associated with an open file or data stream.
0: stdin (standard input)
1: stdout (standard output)
2: stderr (standard error)
Redirect or save the output file to a file:
$ echo "This is a sample text 1" > temp.txt will be emptied before writing.
Additional content:
$ echo "This is sample text 2" >> temp.txt
[Success and failure commands: When a command fails, it returns a non-zero exit code, and 0 represents normal completion of execution. The status value can be read from the special variable $?. Run echo $? immediately after the command execution statement to print the exit status]
The following command prints stderr text to the screen instead of outputting it to a file. And since there is no stdout output, out.txt is empty:
$ ls + > out.txt
The following command redirects stderr to out.txt:
$ ls + 2> out.txt
You can redirect stderr to a file and stdout to another file like:
$ cmd 2>stderr.txt 1>stdout.txt
It is also possible to redirect both stderr and stdout to the same file, by converting stderr to stdout, for example:
$ cmd 2>&1 out.txt
or
$ cmd &> out.txt
Occasionally, the output may contain unnecessary information (such as debug information). If you don't want the output terminal to piggyback on stderr details, you should redirect stderr output to /dev/null, which will remove the information entirely. $ cmd 2 > /dev/null.
After redirecting the data to a file, pass a copy of the data to subsequent commands. Is through the tee command. In the code below, stdin data is received through the tee command. It writes a copy of stdout to out.txt and sends another copy as stdin to the next command. The cat -n command prepends each line received from stdin with a line number and writes it to stdout:
$ cat a* | tee out.txt | cat -n
. . . . . . . . . . . . . . . . . . unfinished