Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

How to do input/output redirection in Linux

Khizar Hayat Saani

Input/Output (I/O) redirection in Linux refers to the ability of the Linux operating system that allows us to change the standard input (stdin) and standard output (stdout) when executing a command on the terminal.

By default, the standard input device is your keyboard and the standard output device is your screen.

I/O Redirection

Output redirection

We can overwrite the standard output using the ‘>’ symbol.

The right operand is set as the standard output.

In the above example, we first run the ls command to list the files and directories in the root directory onto the standard output.

Then, the same command is run again. However, this time we use the ‘>’ symbol to redirect the standard output to file.txt.

Using the cat command, we output the content of file.txt. Notice that the file contains the output of the previously executed ls command.

Input redirection

We can overwrite the standard input using the ‘<’ symbol.

The right operand is set as the standard input.

In this example, we create a file (file.txt) using the touch command.

The echo command echoes strings onto the standard output. Using output redirection, we redirect the echo command’s output to file.txt. We can see that file.txt now contains a single row with the data hello world.

The wc -l command returns the number of rows in a file followed by the name of the file. By default, the command takes the name of the file from the standard input.

Using the ‘<’ symbol, we redirect the standard input to file.txt.

We get 1 as our output. However, the name of the file is not printed in this case. This happens because the command assumes that it is taking its input from stdin rather than a file. Hence, the name of the file is not printed.

Note: We can also append data to the standard input and output by using the ‘<<’ (stdin) and ‘>>’ (stdout) symbols.



Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring