I/O means Input/Output. Redirection can be define as changing the way from where commands read input to where commands sends output.
Redirections, meta characters are use. Redirection can be into a file (shell meta characters are angle brackets ‘<‘, ‘>’) or a program ( shell meta characters are pipesymbol ‘|’).
Standard Streams In I/O Redirection
Bash shell has three standard streams in I/O redirection.
Here : stdin is standard input and stout standard output.
Standard input (stdin) :
The stdin stream is number as stdin (0). The bash shell takes input from stdin. By default, keyboard is use as input.
Standard output (stdout) :
The stdout stream is number as stdout (1). The bash shell sends output to stdout. Output goes to display.
Standard error (stderr) :
The stderr stream is number as stderr (2). The bash shell sends error message to stderr. Error message goes to display.
Redirection Into A File
Each stream uses redirection commands. Single bracket ‘>’ or double bracket ‘>>’ can be use to redirect standard output.
If the target file doesn’t exist, a new file with the same name will be create.
Overwrite
The overwrite commands with a single bracket ‘>’ overwrite existing file content.
> : standard output
< : standard input
2> : standard error
Here: Writing ‘1>’ or ‘>’ and ‘0<‘ or ‘<‘ is same thing. But for stderr you have to write ‘2>’.
Sample syntax of cat > <filename> :
# cat > <filename>
Like example of cat > command :
# cat > sample.txt
See your terminal after run the command, command “cat > sample.txt” has created ‘sample.txt’ with content ‘a, b, c’. Same file ‘sample.txt’ is create again with command “cat > sample.txt” and this time it overwrites earlier file content and only displays ‘d, e, f ‘.
Append
Commands with a double bracket ‘>>’ do not overwrite the existing file content.
>> - standard output
<< - standard input
2>> - standard error
Sample syntax of cat >> command :
# cat >> <filename>
Like example of cat >> command :
# cat >> sample.txt
See your terminal after run the command, here again we have created two files with the same name using ‘>>’ in command “cat >> sample.txt”.
But this time, content doesn’t overwrite and everything is display.
Redirection Into A Program
The Linux pipe redirects a stream from one program to another. When pipe is use to send standard output of one program to another program.
First program’s data will not be display on the terminal, only the second program’s data will be display.
The functionality of pipe may look similar to that of ‘>’ and ‘>>’ but has a significance difference.
Linux pipe redirects data from one program to another while brackets are only use in redirection of files.
Like example of cat > command :
# ls *.txt | cat > txtFile
See your terminal after run the command, command “ls *.txt | cat > txtFile” has put all the ‘.txt’ files into a newly created file ‘txtFile’.