Redirections
In Linux, whenever an individual runs a command, it can take input, give output, or do both.
Redirection helps us redirect these input and output functionalities to the files or folders we want, and we can use special commands or characters to do so.
These redirections can come in handy when we work with multiple and large outputs or inputs since we can use file data directly as input and store results in files.
All this can be done easily on the terminal using some simple commands.
Types of Redirection
1. Overwrite Redirection
Overwrite redirection is useful when you want to store/save the output of a command to a file and replace all the existing content of that file.
“>” standard output
“<” standard input
2. Append Redirection
With the help of this Redirection, you can append the output to the file without compromising the existing data of the file.
“>>” standard output
“<<” standard input
3. Merge Redirection
This allows you to redirect the output of a command or a program to a specific file descriptor instead of standard output. the syntax for using this is “>&” operator followed by the file descriptor number.
“p >& q” Merges output from stream p with stream q
“p <& q” Merges input from stream p with stream q
4. Error Redirection
Error redirection is transferring the errors generated by some false commands to a file rather than STDOUT.
Whenever a program is executed at the terminal, 3 files are generated: standard input(0), standard output(1), standard error(2). These files are always created whenever a program is run.
By default, an error stream is displayed on the screen.
"2>"
"2>&1"
2(STDERR). Using “2>” re-directs the error output to a file named “error.txt” and nothing is displayed on STDOUT.
2>&1 means that STDERR redirects to the target of STDOUT. More formally, the error message generated by “2” gets merged with the current output “1“.
The error output is merged with the standard output which in turn is being re-directed to “error.txt“.
5. Program Redirection
Pipe redirects a stream from one program to another.
When pipe is used to send standard output of one program to another program, first program's data will not be displayed on the terminal, only the second program's data will be displayed.
Pipe redirects data from one program to another while brackets are only used in redirection of files.
command "ls *.txt | cat > txtFile" has put all the '.txt' files into a newly created file 'txtFile'.
Last updated