stderr
Redirection
We have seen how to redirect the standard output to a file, which is convenient. Another practical operation is to redirect the standard error. The standard output and the standard error are directed to the screen display. So, the output of the command we often see usually includes the standard output and standard error results, such as the following:
Use the cat
command to read two files at the same time, one of which exists and the other does not exist:
cat Documents/test.c hello.c
The command not only outputs the contents of the first file but also shows an error message at the end of the listing.
Then, we redirect the output to a file. However, according to our previous experience, we may not see any output:
cat Documents/test.c hello.c somefile
labex:project/ $ cat Documents/test.c hello.c
#include <stdio.h>
int main()
{
printf("hello world\n");
return 0;
}
cat: hello.c: No such file or directory
labex:project/ $ cat Documents/test.c hello.c somefile
#include <stdio.h>
int main()
{
printf("hello world\n");
return 0;
}
cat: hello.c: No such file or directory
cat: somefile: No such file or directory
Unfortunately, although we have redirected the output to the file, there is still an error message in the terminal listing. Sometimes, we want to hide some errors or warnings. What should we do in such cases? We can use file descriptors to achieve that.
Redirect the standard error to the error.log
, and then redirect the standard output to the terminant:
cat cat Documents/test.c hello.c somefile > /dev/tty 2> error.log
echo
cat error.log
labex:project/ $ cat Documents/test.c hello.c somefile > /dev/tty 2>error.log
#include <stdio.h>
int main()
{
printf("hello world\n");
return 0;
}