How to redirect output to a file and standard output in Linux

Output redirection in Shell script

There are times, we want to display status codes and error messages in standard output device. In addition to that, we want to write them to log file as well for future reference. In this case, we must repeat echo statement. One for standard output device and other for log file. We can avoid this repetition using tee command.

Syntax to redirect the output to a file

Example script

Pipe in Linux

Pipe (|) operator connects ls output to tee command. In other words, it sends output of one command as input to other command.

Tee command in Linux

tee command will allow command output is displayed in screen and stored in log file as well. -a option will ensure future command output are appended to log file. tee command without -a will overwrite the content in log file. So, we used tee -a option to store echo output in log file. After the script is executed, output is shown as below. Further log file  content is also shown to support above explanation.

Standard output after the script execution

Log file output in Linux

Recommended Articles