Issue
I have shell script in Linux like below
#!/bin/bash
LOG_LOCATION=/home/$USER/logs
exec > >(tee /home/$USER/logs/"$1") 2>&1
[ $# -ne 1 ] && { echo "Usage : $0 table ";exit 1; }
table=$1
TIMESTAMP=`date "+%Y-%m-%d"`
touch /home/$USER/logs/${TIMESTAMP}.success_log
touch /home/$USER/logs/${TIMESTAMP}.fail_log
success_logs=/home/$USER/logs/${TIMESTAMP}.success_log
failed_logs=/home/$USER/logs/${TIMESTAMP}.fail_log
#Function to get the status of the job creation
function log_status
{
status=$1
message=$2
if [ "$status" -ne 0 ]; then
echo "`date +\"%Y-%m-%d %H:%M:%S\"` [ERROR] $message [Status] $status : failed" | tee -a "${failed_logs}"
#echo "Please find the attached log file for more details"
exit 1
else
echo "`date +\"%Y-%m-%d %H:%M:%S\"` [INFO] $message [Status] $status : success" | tee -a "${success_logs}"
fi
}
`hive -e "create table testing.${table} as select * from fishing.${table}"`
cp /home/$USER/logs/"$1" /home/$USER/debug/"$1"
g_STATUS=$?
log_status $g_STATUS "Hive create ${table}"
echo "***********************************************************************************************************************************************************************"
If I have this in my shell script
exec 2>&1 | tee /home/logging/"$1"
Then I am getting logs only on console not on the redirected file.
If I have this in my script
exec> /home/logging/"$1" 2>&1
Then I am having logs on the redirected file but not on the console.
How can I have logs both on console and redirected file
Solution
You can use process substitution with exec
builtin:
exec > >(tee trace.log) 2>&1
to redirect both stdout and stderr to a file as as well as show it in terminal.
Answered By - anubhava Answer Checked By - David Goodson (WPSolving Volunteer)