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

output of shell script to console and file

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

#!/bin/bash
LOG_LOCATION=/home/$USER/logs
exec > >(tee /home/$USER/logs/"") 2>&1

[ $# -ne 1 ] && { echo "Usage : [=11=] table ";exit 1; }

table=

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=
       message=
       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/"" /home/$USER/debug/"" 

g_STATUS=$?
log_status $g_STATUS "Hive create ${table}"

echo "***********************************************************************************************************************************************************************"

如果我的 shell 脚本中有这个

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

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

如果我的脚本中有这个

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

然后我在重定向的文件上有日志,但在控制台上没有。

我怎样才能在控制台和重定向文件上都有日志

您可以使用 exec 内置的进程替换:

exec > >(tee trace.log) 2>&1

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

tee 命令的目的专门用于将输出定向到文件和终端,这听起来就像您想要的那样。这可以很容易地用类似下面的东西复制:

script.sh:

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

然后,运行带有./script.sh abc.txt的命令将向终端生成日期命令的输出以及文件abc.txt

在您的情况下,exec 2>&1 | tee /home/logging/"" 应该可以正确地产生您想要的结果,但是您需要小心地使用该参数调用脚本。假设 /home/logging 目录存在,并且您使用类似 ./script log.txt

的内容调用上面的脚本