How to redirect output to a file and standard output in Linux
Contents
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
1 |
<command> | tee -a <log_file> |
Example script
1 2 3 4 5 6 7 |
$cat tee.sh #!/usr/bin/bash ls | tee tee.log echo "end of script" | tee -a tee.log $chmod +x tee.sh $./tee.sh |
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
1 2 3 4 |
/revisit/user1/sample.txt /revisit/user1/hello.sh /revisit/user1/tee.sh end of script |
Log file output in Linux
1 2 3 4 5 |
$cat tee.log /revisit/user1/sample.txt /revisit/user1/hello.sh /revisit/user1/tee.sh end of script |
Recommended Articles
- How to append Timestamp to file name in Shell script?
- How to parse input arguments with tokens in Bash script?