Shell

How to redirect stdout and stderr to log file

terminal bash shell How to redirect standard output and standard error to a log file

Correctly redirecting stdout and stderr to a log file

command > /path/to/log 2>&1

The system redirects stdout to the log file, then redirects stderr to stdout. As a result, both stdout and stderr go to the log file. For example: Test redirection with ls -l.

[tum@ezylinux test]$ ls -l > log2 2>&1

Check the file contents to see the redirected output.

[tum@ezylinux test]$ cat log2
total 0
-rw-rw-r-- 1 t1sb t1sb 0 Nov  3 17:02 log2

Test redirection with lss -l (intentionally causing an error).

[tum@ezylinux test]$ lss -l > log2 2>&1

Check the file contents to see the redirected error.

[tum@ezylinux test]$ cat log2
-bash: lss: command not found

Incorrectly redirecting stdout and stderr to a log file

command 2>&1 > /path/to/log

The system redirects stderr to stdout, which still points to the console, then redirects stdout to the log file. Errors therefore appear on the console, while normal output is redirected to the log file. Test redirection with ls -l.

[tum@ezylinux test]$ ls -l 2>&1 > log2

Check the file contents to see the redirected output.

[tum@ezylinux test]$ cat log2
total 0
-rw-rw-r-- 1 t1sb t1sb 0 Nov  3 17:00 log2

Test redirection with lss -l (intentionally causing an error). The error appears on the console instead of being written to the file.

[tum@ezylinux test]$ lss -l 2>&1 > log2
-bash: lss: command not found

Check the file for the redirected error; no error will be present.

[tum@ezylinux test]$ cat log2
EOF.← Back to articles