如何在Linux / bash

时间:2017-04-28 19:55:09

标签: linux bash shell logging

我有一个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    

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

1 个答案:

答案 0 :(得分:2)

更改

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在循环的迭代中发生了变化,因此您希望在所有表上运行的任何命令都需要在循环内运行。