I/O Redirection in Linux

·

3 min read

I/O Redirection in Linux

Hey there👋🏻! This article is all about Input Output Redirection in Linux. These are very useful when you want to save any output in a file or use a file as input to a program. We will also learn a bit about File Descriptor.

File Descriptor

A file descriptor is an integer number that uniquely represents open files in a system. The file descriptor for stdin, stdout and stderr is assigned as 0, 1 and 2 respectively.

When any command runs with a success then its file descriptor would be 0. You can use echo $? to get the file descriptor of the previous command.

$ cat input
Rohini Chandra
$ echo $?
0

Types of IO Redirections

There are 3 types of IO Redirects, mainly;

  • Standard Input (stdin) -> Typing commands in a terminal.
  • Standard Output (stdout) -> Output displayed in a terminal after executing a command.
  • Standard Error (stderr) -> When a command is executed with an error.

✨Redirect Standard Output

To redirect command output to a file we use > and >> (greater than) symbols. > saves the output in a file. You can create the file while routing the output or use an existing one.

o_redirect.PNG

echo command simply displays the output in a terminal. If we want to route it to a file, we can do that using >. But this will replace the text if the same file is used again.

To append output in an existing file, we use >>. Without overriding the data in an existing file, it will append the output in the same file.

o_redirect2.PNG

✨Redirect Standard Input

To use a file as an input to a command we make use of < and << (lesser than) symbols. One use case is when we want to use a SQL file to populate a database.

mysql -u username -p database_name < file.sql

✨Redirect Standard Error

To redirect error output to a file we use 2> where 2 represents stderr. This means that only errors will be routed to the file. ls command lists all the files and directories of a current working directory. We will make use of this command to get a better understanding.

e_redirect.PNG

Here in the above example, we try to list input_directory and output_directory where we don't have the output_directory directory. So, the error will be sent to the error file and ls will list the output for input_directory.

2>&1 means error and success output will be redirected to the same file.

$ ls input_directory output_directory > error 2>&1
$ cat error
ls: cannot access 'output_directory': No such file or directory
input_directory:
input

If we want error and output in two different files,

ls input_directory output_directory > success 2> error

Thank you for reading this blog 😇!