3.3 Standard error



When you operate computer, various errors are happened. To communicate error, the computer uses its screen. Let's consider the following case.

Example

$ ls -l no-exist-file > ls-l-output ↵       (Redirect details of 'no-exist-file' to ls-output)
ls: no-exist-file: No such file or directory       (Error Message about not existing)


This command tries to output the details of the file named "no-exist-file" to the file named "ls-l-output". However, if the file not exists, what happens? If the error message outputs to standard output, when the redirection works, the error message also saves to "ls-l-output", so the error message can not reach to the user.

In UNIX, it is generally determined to output the error message to the standard error. As a result, even if a standard output is redirected to the file, the error message can be checked.
In addition, it is also possible to redirect the standard error to the file as follows.

Example

$ ls -l no-exist-file 2> ls-l-output ↵       (Redirect error output to ls-l-output)


In this case, the error message does not appear on the screen and it is output to the file. It is available when you want to check the operation or record the error output contents.

2 indicates the standard error. The standard output is 1. If you want to mix the standard output with the standard error and output it, enter as follows.

Example

$ ls -l no-exist-file > ls-l-output-second 2>&1
↵              (Redirect standard output and standard error to ls-l-output-second)


Be careful the position to specify a file name, 1, and 2.


Practice: Save error message to a file


Let's save error message to a file, actually


$ ls -l no-exist-file 2> ls-l-output ↵ $ cat ls-l-output ↵ ls: no-exist-file: No such file or directory $ ls -l no-exist-file > ls-l-output-second 2>&1 ↵ $ cat ls-l-output-second ↵ ls: no-exist-file: No such file or directory


If you do not want to display neither standard output nor standard error, you can redirect it to a special file, which is called null device (/dev/null).


$ ls -l no-exist-file > /dev/null 2>&1 ↵

(As the result of redirecting both standard output and standard error into null device, nothing displays)



Previous Next