Redirection in Unix/Linux

Redirection is a very important concept in Unix, it is quite helpful when you setup cron or schedule the scripts, it helps you in redirection output from std device like screen to some file which can be beneficial if script is running in the background without user interference. Any person can later check the output redirected from a script to a log file, which is quite helpful for system admins. Before proceeding further we should know 2 terms:

  1. standard output STDOUT- Standard output is the stream where a program writes its output data
  2. standard error STDERR – Standard error is another output stream typically used by programs to output error messages or diagnostics. It is a stream independent of standard output and can be redirected separately
  3. Standard Input STDIN – Standard input is stream data (often text) going into a program
Streams

Fig. Streams Src – Wikipedia

Below is the syntax & their meaning.

 

Character Action
> Redirect standard output
2> Redirect standard error
2>&1 Redirect standard error to standard output
< Redirect standard input
| Pipe standard output to another command
>> Append to standard output
2>&1| Pipe standard output and standard error to another command

Some examples:

  • Cat a file which is not present:
cat abc.txt  > std_out.log
cat: abc.txt: No such file or directory
ls -l std_out.log
0 std_out.log

Since the file is not present it is giving stderr on Screen, Also since no std output std_out.log is size 0

  •  Cat a file and redirect stderr to some log file
    cat abc.txt  2> std_err.log
    ls -l std_err.log
    40 std_err.log
    cat std_err.log
    cat: abc.txt: No such file or directory
    
  • Redirect STDERR & STDOUT in separate files
cat abc.txt > std_out.log  2>std_err.log
ls -lrt *
0 - std_out.log
40 - std_err.log
cat std_err.log
cat: abc.txt: No such file or directory
  • Redirect STDERR & STDOUT in same file:
     cat abc.txt > process.log 2>&1
    ls -lrt process.log 
    40 process.log
    cat process.log
    cat: abc.txt: No such file or directory
    

You might be wondering about & before 1 that is a syntax basically, if not given it will just redirect the stderr to a file named 1, 1 is symbol for Standard Out

You can also use /dev/null if you just want to discard the output, all data is lost which is redirected is /dev/null as that is kinda black hole.

0 comments