CyberKeeda In Social Media

BASH : Redirection STDOUT and STDERR into a file using 2>&1





How to redirects script output or error outputs
Let take three files named as  file1, file2, file3

Every file has the same content as " Hello World "
cybeerkeeda@Linux-Maniac:~ cat file1 file2 file3 
Hello World
Hello World
Hello World
Now lets assume fourt file named as file4 , which doesn't  exists 
cybeerkeeda@Linux-Maniac:~ cat file1 file2 file3 file4
Hello World
Hello World
Hello World
cat: file4: No such file or directory
Now compare with some of your shell script, you might want to log the errors or whole output into a file, in that case redirection comes into picture.

Case 1 : If you want to log every STDOUT irrespective of expected output or Errors, you can use the below parameter along with your shell script.
cybeerkeeda@Linux-Maniac:~ cat file1 file2 file3 file4   > mylog.txt  2>&1
Case 2 : If you want to log only STDERR ( Errors ), you can use the below parameter along with your shell script.

cybeerkeeda@Linux-Maniac:~ cat file1 file2 file3 file4   2> outfile

The above set of example will be used in log custom shell scripts outputs ( STDOUT / STDERR ) and one more example of it's usage in cron too.

Here is an example, usage of redirection with 2 and 1 to stop cron job sending mail for each execution. 




No comments:

Post a Comment

Designed By Jackuna