Wednesday, September 12, 2012

Redirect Errors and Output to a file


To pass only errors to a file, use below syntax. 

Command 2> err.txt 

For example :

Create a blank directory 
mkdir test1
cd test1

Create some blank files
touch file1
touch file2
touch file3

ls -lrt file*
-rw-r--r--  1 sunilsagar  staff  0 Sep 12 23:13 file3
-rw-r--r--  1 sunilsagar  staff  0 Sep 12 23:13 file2
-rw-r--r--  1 sunilsagar  staff  0 Sep 12 23:13 file1

ls -lrt file5
ls: file5: No such file or directory

Now redirecting error to one file.
ls -lrt file5 2> err.txt

cat err.txt 
ls: file5: No such file or directory

Similarly, this can be used for transferring errors to a file, very popular in shell scripting


some command 2> /dev/null

For transferring error free output use tee, this will insert as well as redirect output to a file.

For example:

cat file* | tee out.txt | cat -n

cat - this will open the file
tee will display and redirect output
cat -n will list the file that were opened during the execution of command.