Linux Output Redirection

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Linux Output Redirection

Output redirection is used to put output of one command into a file or into another command.

> stdout

The stdout is redirected with a '>' greater than sign. When shell meets the '>' sign, it will clear the file (as you already know).

Example:

 

  1. echo Hello everyone. > afile.txt   

Linux Output Redirection1

Look at the above snapshot, greater than sign '>' redirects the command 'echo' output into a file 'afile.txt'.

Output File Is Erased

In output redirection, during scanning of a command line, shell will encounter through '>' sign and will clear the file.

Example:

  1. zcho Welcome > afile.txt  

Linux Output Redirection2

Look at the above snapshot, command "zcho Welcome > afile.txt" is wrong but still file 'afile.txt' is cleared.

noclobber

We can prevent file deletion while using '>' sign with the help of noclobber option.

Syntax:

  1. set -o noclobber    (To prevent overwrite)  
  2. set +o noclobber    (To overwrite) 

Example:

echo Learn Linux. > newfile.txt 

Linux Output Redirection3

Look at the above snapshot, command "set -o noclobber" prevents file from getting overwrite.

But command "set +o noclobber" allows you to overwrite the existing file.

Overruling noclobber

Overruling noclobber means you can overwrite an existing file while noclobber is set by using '>|' sign.

Syntax:

command ><fileName>

Example:

echo Welcome to JavaTpoint. >| newfile.txt 

Linux Output Redirection4

Look at the above snapshot, with greater than '>' sign, bash doesn't allow to overwrite the file 'newfile.txt'. But with '>|' sign file is overwritten.


>>append

Append '>>' sign doesn't let the file content to be overwritten and hence, displays new as well as old file content.

Syntax:

  1. command >> <fileName>  

Example:

echo You all are welcome here. >> newfile.txt 

Linux Output Redirection5

Look at the above snapshot, file 'newfile.txt' is not overwritten with append command. New content is displyed with the old one.