« iLaugh | Main | Nailed it down »

Pipes and redirections in sh

A quick reference to pipes and redirections in sh.

Notes

In sh, the standard output is identified as file descriptor 1 and the diagnostic output as file descriptor 2.

Pipes

  • Use the standard output of program_1 as the standard input of program_2:

    program_1 | program_2
    
  • Use the standard and diagnostic outputs of program_1 as the standard input of program_2:

    program_1 2>&1 | program_2
    

Redirections

  • Open file name as the standard input:

    program < name
    
  • Use file name as the standard output:

    program > name
    
  • Append the output to the end of file name:

    program >> name
    
  • Route both the standard and diagnostic outputs to file name:

    ( program 2>&1 ) > name
    
  • Append both the standard and diagnostic outputs to file name:

    ( program 2>&1 ) >> name
    

Tips

  • To route the standard and diagnostic outputs to separate files, use the following syntax:

    program > outfile 2> errfile
    
  • To route the diagnostic output to a file and the standard output to the terminal, use:

    program 2> errfile
    
  • To retain only the diagnostic output, redirect the standard output to /dev/null:

    program > /dev/null
    program > /dev/null 2> errfile
    
  • In order to test pipes and redirections, use the following Perl program:

    #!/usr/bin/perl
    
    
    print STDOUT "STDOUT: Standard output\n";
    print STDERR "STDERR: Diagnostic output\n";
    

TrackBack

TrackBack URL for this entry: https://ithink.ch/blog/tb.cgi/60.

Make sure JavaScript is enabled before using this URL. If you would like to ping my blog but can't, please do send me an e-mail at os3476 at this domain.

Post a comment

Make sure JavaScript is enabled before posting a comment. If you would like to post a comment but can't, please do send me an e-mail at os3476 at this domain.

Do not meddle in the affairs of Coding Ninjas, for they are subtle and quick to anger.