Redirection

Redirection batch programming is a very useful tool. Almost all the IT staff to use these tools. Redirection batch programs can provide input and output in accordance with what we expect.
I already use it for mecopy result of a processed like PING. Where the use of ping is to know the certainty of the opposite device in front of us or far from where we are.

There are several kinds of input and output referred to in this article, each with an identifier that can be used to refer to them on the command line:

  • STDIN : the keyboard, 0
  • STDOUT : the screen, 1
  • STDERR : error output, 2

In addition, there are several operators which can be used to redirect the data in the system:

  • > output redirection
  • >> append output redirection
  • < input redirection
  • | pipe redirection

The Output Redirection Operator >

This is used to send output from a command to a file, or other location, as specified by the various locations specified above. If the file does not exist, it will be created. If it does exist, it will be truncated before any data is written, without warning.

To put a directory listing in a text file, for example, the following could be used:

dir > dir-test.txt

The Append Redirection Operator >>

Like the output redirection operator, the >> operator opens the file with write only access, but it does not truncate it.

So, to periodically ping a known location to check network status, it might be useful to redirect the ping command output to a status file:

ping -t www.google.com >> ping_status_google.txt

The Input Redirection Operator <

Redirecting input is useful because it allows the programmer to build up a file with output redirection, and then use that output in conjunction with another command, as input. For example, a file can be sorted, line by line, using the sort command:

sort < testfile.txt

This can be used, for example, to sort a directory listing:

C:\>dir /b listdirectory.txt
C:\>sort listdirectory.txt

The Pipe Operator |

Finally, the | operator can be used to send the output of one command to the input of another. So, to create a sorted list of files, without passing through an intermediate text file, the following is used:

dir /b | sort

Again, output can be redirected to create a sorted file list:

dir /b | sort > List-Directory.txt