shell脚本输出到控制台和文件

时间:2017-04-19 17:29:34

标签: linux bash shell stdout stderr

我在Linux下有shell脚本,如下所示

#!/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 "***********************************************************************************************************************************************************************"

如果我在我的shell脚本中有这个

exec 2>&1 | tee /home/logging/"$1"

然后我只在控制台上获取日志而不是重定向文件。

如果我在我的剧本中有这个

exec> /home/logging/"$1" 2>&1

然后我登录重定向文件,但没有登录控制台。

如何在控制台和重定向文件上都记录日志

2 个答案:

答案 0 :(得分:1)

您可以使用exec builtin:

进行流程替换
exec > >(tee trace.log) 2>&1

将stdout和stderr重定向到文件,并在终端中显示它。

答案 1 :(得分:0)

tee命令的目的是专门用于将输出定向到文件和终端,这听起来像是你想要的。这可以通过以下方式轻松复制:

script.sh:

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

然后,使用./script.sh abc.txt运行命令将生成date命令到终端的输出以及文件abc.txt

在您的情况下,exec 2>&1 | tee /home/logging/"$1"应该正确地生成您想要的结果,但您需要仔细调用带有该参数的脚本。这假定/home/logging目录存在,并且您使用./script log.txt

之类的内容调用上面的脚本
相关问题