Javatpoint Logo
Javatpoint Logo

Linux I/O Redirection

Redirection can be defined as changing the way from where commands read input to where commands sends output. You can redirect input and output of a command.

For redirection, meta characters are used. 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

The bash shell has three standard streams in I/O redirection:

  • standard input (stdin) : The stdin stream is numbered as stdin (0). The bash shell takes input from stdin. By default, keyboard is used as input.
  • standard output (stdout) : The stdout stream is numbered as stdout (1). The bash shell sends output to stdout. Output goes to display.
  • standard error (stderr) : The stderr stream is numbered 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 used to redirect standard output. If the target file doesn't exist, a new file with the same name will be created.

Overwrite

Commands with a single bracket '>' overwrite existing file content.

  • > : standard output
  • < : standard input
  • 2> : standard error

Note: Writing '1>' or '>' and '0<' or '<' is same thing. But for stderr you have to write '2>'.

Syntax:

Example:

Linux I/O Redirection1

Look at the above snapshot, command "cat > sample.txt" has created 'sample.txt' with content 'a, b, c'. Same file 'sample.txt' is created 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

Syntax:

Example:

Linux I/O Redirection2

Look at the above snapshot, 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 displayed.


Redirection Into A Program

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.

Although the functionality of pipe may look similar to that of '>' and '>>' but has a significance difference. Pipe redirects data from one program to another while brackets are only used in redirection of files.

Example:

Linux I/O Redirection3

Look at the above snapshot, command "ls *.txt | cat > txtFile" has put all the '.txt' files into a newly created file 'txtFile'.





Please Share

facebook twitter google plus pinterest

B.Tech / MCA


Learn Latest Tutorials