Redirection in Linux

Redirection

  
whenever we execute a command, it shows its output on the terminal window only. But, if you want this output to be saved in a file then concept of redirection comes in picture.


  • STDOUT



> (Greater than) is used for redirecting output to a file


example_Screenshot


so whenever we use >, the output is saved to a new file. But if you want to redirect its output to an existing file then you have to use >> else your previous data will be lost.


Example_Screenshot

TO verify this you can see below screenshot.


Example_Screenshot

 Now appended content screenshot


Example_Screenshot

  • STDIN 

     

     < (less than) is used for redirecting input to file.


    if you want to do some operation on the file. like counting number of words, lines.. etc in a file.

    Example Screenshot

    Note the difference, when you are using redirection, your file name is not shown because during redirection file is sent anonymously.
     
you can also easily combine STDIN and STDOUT. e.g. you want to process a file and want to save the output into a new file then this combination is useful.
Example Screenshot


Note: you can also use 0> for STDIN and >1 for STDOUT.


  • STDERR
This stream has value 2 and it will be used as 2>.

ls video.mp4 2> error.txt
If video.mp4 is not present in your file directory then you will get an error- 
ls: cannot access 'video.mp4': No such file or directory

and this error will be saved to a new file error.txt.

If you want to append the errors in an existing file then you must use 2>>.

if you want to save output and error both then you can do this like

ls -l video.mp4 file.txt > myoutput  2>&1 
video.mp4 is not in your system and file.txt is inside your home directory. so whenever you will run above code. it will make a new file myoutput and save the error as well as output in file named myoutput.


You can read about pipe here.
Related Posts Plugin for WordPress, Blogger...