Redirect echo output in shell script to logfile Redirect echo output in shell script to logfile shell shell

Redirect echo output in shell script to logfile


You can add this line on top of your script:

#!/bin/bash# redirect stdout/stderr to a fileexec >logfile.txt 2>&1

OR else to redirect only stdout use:

exec > logfile.txt


I tried to manage using the below command. This will write the output in log file as well as print on console.

#!/bin/bash# Log Location on Server.LOG_LOCATION=/home/user/scripts/logsexec > >(tee -i $LOG_LOCATION/MylogFile.log)exec 2>&1echo "Log Location should be: [ $LOG_LOCATION ]"

Please note: This is bash code so if you run it using sh it will through syntax error


You can easily redirect different parts of your shell script to a file (or several files) using sub-shells:

{  command1  command2  command3  command4} > file1{  command5  command6  command7  command8} > file2