stdout, stdin

Howto redirect the standard input and output of a command shell script:

STDERR and STDOUT together:

    $output = `cmd 2>&1`;

To capture a command’s STDOUT but discard its STDERR:

    $output = `cmd 2>/dev/null`;

To capture a command’s STDERR but discard its STDOUT (ordering is important here):

    $output = `cmd 2>&1 1>/dev/null`;

To exchange a command’s STDOUT and STDERR in order to capture the STDERR but leave its STDOUT to come out the old STDERR:

    $output = `cmd 3>&1 1>&2 2>&3 3>&-`;

To read both a command’s STDOUT and its STDERR separately, it’s easiest to redirect them separately to files, and then read from those files when the program is done:

    system("program args 1>program.stdout 2>program.stderr");
  • Yes, but if you write them to files, how will you match up or interleave the normal output and the error messages associated with them afterwards?

  • Because when the files are seperated you give a explicite name to them. Otherwise (when you write them to one file) you dont’t know 🙂 or you can redirect each one to a simple script which add a line, #### I am stout / #### I am sterr, in the same file!