【问题标题】:How to create status logs for shell script in Linux/bash如何在 Linux/bash 中为 shell 脚本创建状态日志
【发布时间】:2017-04-28 19:55:09
【问题描述】:

我有一个 shell 脚本。对于这个脚本,我从一个文件传递参数。此文件包含表名

脚本运行良好。我可以对文件中的所有表执行命令。

shell script

#!/bin/bash

[ $# -ne 1 ] && { echo "Usage : $0 input file "; exit 1; }
input_file=$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
}

while read table ;do 
  sqoop job --exec $table > /home/$USER/logging/"${table}_log" 2>&1
done < ${input_file}

g_STATUS=$?
log_status $g_STATUS "Sqoop job ${table}"

我正在尝试为脚本收集status logs

我想分别为每张桌子收集status logs

我想要什么

2017-04-28 20:36:41 [ERROR] sqoop job table1 EXECUTION [Status] 2 : failed
2017-04-28 20:36:41 [ERROR] sqoop job table2 EXECUTION [Status] 2 : failed

我得到了什么

如果最后一个表的脚本失败

2017-04-28 20:38:41 [ERROR] sqoop job EXECUTION [Status] 2 : failed 

如果最后一个表的脚本成功则

2017-04-28 20:40:41 [ERROR] sqoop job [Status] 0 : success    

我做错了什么以及我应该做出哪些改变才能获得理想的结果。

【问题讨论】:

  • 将代码中的最后两行移至while 循环内。否则,它只会在循环的最后一次迭代中运行。
  • @Munir 你的意思是g_STATUS=$?log_status $g_STATUS "Sqoop job ${table}"这两行
  • 是的...这两行
  • @Munir 谢谢它工作得很好我得到了想要的结果
  • @Munir 一个简单的问题。假设如果想为每个表将/home/$USER/logging/"${table}_log" 复制到 Linux 中的不同位置。我怎样才能做到这一点?我试过cp /home/$USER/logging/"${table}_log" /home/$USER/debug/date "+%Y-%m-%d"/logs/。它说找不到/home/$USER/logging/"_log"没有这样的文件或目录

标签: linux bash shell logging


【解决方案1】:

改变

while read table ;do 
  sqoop job --exec $table > /home/$USER/logging/"${table}_log" 2>&1
done < ${input_file}

g_STATUS=$?
log_status $g_STATUS "Sqoop job ${table}"

while read table ;do 
  sqoop job --exec $table > /home/$USER/logging/"${table}_log" 2>&1
  g_STATUS=$?
  log_status $g_STATUS "Sqoop job ${table}"
  # Any other command you want to run on using $table should be placed here
done < ${input_file}

while 循环仅运行whiledone 行内的代码。因此,要记录所有表,您需要在 while 循环内运行日志记录。

另外,$table 循环的迭代发生了变化,因此您想要在所有表上运行的任何命令都需要在循环内运行。

【讨论】:

  • 一个简单的问题假设我想为上述脚本中的每个失败作业发送一封电子邮件,或者为input_file 的所有失败作业发送一封电子邮件我需要做什么更改
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
相关资源
最近更新 更多