Monday, January 4, 2016

HOWTO Redirect Error Output To a File on Linux

First of all, let's start with some Basics:

Bash / ksh and other modern shell on Linux has three file descriptors:

    stdin (0)
    stdout (1)
    stderr (2)

HOWTO redirect output (stdout) to a file:
command-name >  output.txt
command-name >  stdout.txt

HOWTO redirect all errors (stderr) to a file:
command-name 2> errors.txt
command-name 2> stderr.txt

HOWTO redirect both output (stdout) and errors (stderr) to different files:
command1 > out.txt 2> err.txt
command2 -f -z -y > out.txt 2> err.txt

HOWTO redirect both output (stdout) and errors (stderr) to the same file:
command1 > everything.txt 2>&1
command1 -arg > everything.txt 2>&1

HOWTO redirect errors (stderr) to null or zero devices:

Note: Data written to a null or zero special file is discarded by your system. This is useful to silence out errors (also know as 'error spam'):

command1 2> /dev/null
command1 2> /dev/zero
command2 -arg 2> /dev/null
command2 -arg 2> /dev/zero

Tip: Use tee command to redirect to both a file and the screen same time:

command1 |& tee log.txt
or
command1 -arg |& tee log.txt
or
command1 2>&1 | tee log.txt

Another usage:

#!/bin/bash
foo(){
 :
} 2>&1 | tee foo.log

OR

#!/bin/bash
{
   command1
   command2
} 2>&1 | tee script.log