user7543621
user7543621

Reputation:

How to output in a shell script to the console and on a file?

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

Upvotes: 4

Views: 14304

Answers (2)

Alec Bennett
Alec Bennett

Reputation: 5887

The purpose of the tee command is specifically intended to direct the output to both a file and to the terminal, which is what it sounds like you're wanting. This can be replicated pretty easily with something like the following:

script.sh:

#!/usr/bin/bash
date 2>&1 | tee "$1"

Then, running the command with ./script.sh abc.txt will produce the output of the date command to the terminal as well as the file abc.txt

In your case, exec 2>&1 | tee /home/logging/"$1" should correctly produce the results you want, but you will need to call the script with that argument carefully. That assumes the /home/logging directory exists, and you call the script above with something like ./script log.txt

Upvotes: 1

anubhava
anubhava

Reputation: 784888

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.

Upvotes: 5

Related Questions