Pages

Friday, June 2, 2017

Learn The Basics of How Linux I/O (Input/Output) Redirection Works

One of the most important and interesting topics under Linux administration is I/O redirection. This feature of the command line enables you to redirect the input and/or output of commands from and/or to files, or join multiple commands together using pipes to form what is known as a “command pipeline”.
All the commands that we run fundamentally produce two kinds of output:
  1. the command result – data the program is designed to produce, and
  2. the program status and error messages that informs a user of the program execution details.
In Linux and other Unix-like systems, there are three default files named below which are also identified by the shell using file descriptor numbers:
  1. stdin or 0 – it’s connected to the keyboard, most programs read input from this file.
  2. stdout or 1 – it’s attached to the screen, and all programs send their results to this file and
  3. stderr or 2 – programs send status/error messages to this file which is also attached to the screen.
Therefore, I/O redirection allows you to alter the input source of a command as well as where its output and error messages are sent to. And this is made possible by the “<” and “>” redirection operators.

How To Redirect Standard Output to File in Linux

You can redirect standard output as in the example below, here, we want to store the output of the top command for later inspection:
$ top -bn 5 >top.log
Where the flags:
  1. -b – enables top to run in batch mode, so that you can redirect its output to a file or another command.
  2. -n – specifies the number of iterations before the command terminates.
You can view the contents of top.log file using cat command as follows:
$ cat top.log
To append the output of a command, use the “>>” operator.
For instance to append the output of top command above in the top.log file especially within a script (or on the command line), enter the line below:
$ top -bn 5 >>top.log
Note: Using the file descriptor number, the output redirect command above is the same as:
$ top -bn 5 1>top.log

How To Redirect Standard Error to File in Linux

To redirect standard error of a command, you need to explicitly specify the file descriptor number, 2 for the shell to understand what you are trying to do.

      ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
                                                    ► Read more: http://adf.ly/1n5Yse
      ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

No comments:

Post a Comment