Redirection of Output of a Program into another Program - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Redirection of Output of a Program into another Program

Share This

In Linux environment, I/O redirection represents the way by which commands read input and send output.

Redirection can be performed by

  • using > for sending to a file and < for receiving from a file,
  • and using | for a program.

Standard Streams in I/O Redirection

There are three standard streams in Bash shell for I/O redirection:

Standard Input (stdin): By default, the keyboard is used as standard input in the bash shell and it is numbered as stdin (0).
Standard Output (stdout): Similarly, the bash shell sends output to the display unit (screen) and it is numbered as stdout (1).
Standard Error (stderr): In the bash shell, the error message goes to the display unit (screen) again, similar to stdout and it is numbered as stderr (2).

Standard Output Redirection into a File

If you want to redirect the output of a command to a file, you can use > symbol. For example, if you want to redirect the output of ls -l command into a file output.txt, you can use ls -l > output.txt. In this case, if the file output.txt does not exist in your present working directory, a file will be created by this name and if the file exists, previous content will be overwritten by new output of the command.

If you want to redirect the output into a file, but you want to append the output with the previous content of the file, instead of overwriting, you can use >> instead of >.

Note that if you apply output redirection, the output of the command will not be displayed.

Standard Input Redirection from a File

If you want to run a command, which will receive input data from a file instead of receiving the data from the terminal, you can use input redirection. For example, if you have written a shell script (myscript.sh) which will calculate the number of words, number of lines, special symbols of a text, written in a file, sample.txt. You can redirect sample.txt as input to the program.

To do this, you can run ./myscript.sh < sample.txt

Redirection of Output of a Program into another Program

The symbol pipe, |, is used to redirect a stream from one program to another program. Hence, the output of the first program will not be displayed on the terminal.

For example, if you want to concatenate the content of all the files in the present working directory with .txt extension, you can run the following command.

ls *.txt | cat > output.txt

In the above discussion, we have mentioned how to use redirection techniques. Remember that > is used instead of 1> and < is used instead of 0<. But in case of standard error, you have to use 2>.



Happy Exploring!

No comments:

Post a Comment