Bash – how to redirect stderr to stdout or file

On Linux or Unix, error from a command (stderr) can be redirected to stdout or a file. These are the file descriptor id used on Linux for stdin, stdout and stderr.

ID Purpose
0 stdin (Standard input)
1 stdout (Standard output)
2 stderr (Standard error)

stderr appended to stdout example

This can be useful when executing bash command from other programs like php shell_exec.

ls /etc/passwd_non_existing 2>&1 
ls: cannot access /etc/passwd_non_existing: No such file or directory
Env: GNU bash, version 4.3.11

stderr appened to stdout and both redirected to a file

ls /etc/passwd_non_existing > tmp_file_all 2>&1
echo "==tmp_file_all=="
cat tmp_file_all
==tmp_file_all==
Env: GNU bash, version 4.3.11

Only stderr redirected to file example

ls /etc/passwd_non_existing 2> tmp_file_err
echo "==tmp_file_err=="
cat tmp_file_err
==tmp_file_err==
Env: GNU bash, version 4.3.11
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments