You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shell脚本内自动记录所有操作至带日期的日志文件

问题描述

当前通过Putty运行.sh脚本时,每次都要手动执行sh /filepath/file.sh >> /filepath/file_date.log来记录日志,需反复确认重定向路径和文件名,操作繁琐。希望在脚本内配置自动日志记录:

  • 捕获所有操作输出(包括Hive的Map/Reduce更新等)
  • 日志文件名包含运行日期,格式为/filepath/filename_$tday.log
  • 不在控制台显示任何内容

原脚本内容:

#!/bin/bash
set -x

frstdt=`date -d "last monday - 2 week" +"%m%d%Y"`;
scnddt=`date -d "last sunday - 1 week" +"%m%d%Y"`;
tday=`date -d "$date" +"%m_%d_%Y"`;
frstdtem=`date -d "last monday - 2 week" +"%m/%d/%Y"`;
scnddtem=`date -d "last sunday - 1 week" +"%m/%d/%Y"`

cd /filepath/
/filepath/cloak-hive -f query.hql

--Here I use hive -e to get some results from the query and write them to a .csv file.

ehco "Contents of email" | mailx -s "Subject" -a "Attchement" -me@email.com
修改后的脚本
#!/bin/bash
set -x

# 定义日志路径和文件名
LOG_DIR="/filepath"
tday=$(date +"%m_%d_%Y")  # 修正原date命令的多余参数问题
LOG_FILE="${LOG_DIR}/filename_${tday}.log"

# 将标准输出和标准错误全部重定向到日志文件,控制台无输出
exec &> "${LOG_FILE}"

# 原脚本的日期变量定义(保留逻辑)
frstdt=$(date -d "last monday - 2 week" +"%m%d%Y")
scnddt=$(date -d "last sunday - 1 week" +"%m%d%Y")
frstdtem=$(date -d "last monday - 2 week" +"%m/%d/%Y")
scnddtem=$(date -d "last sunday - 1 week" +"%m/%d/%Y")

cd /filepath/
/filepath/cloak-hive -f query.hql

# 这里用hive -e导出结果到csv(示例)
# hive -e "SELECT * FROM your_table WHERE dt BETWEEN '${frstdtem}' AND '${scnddtem}'" > /filepath/result.csv

echo "Contents of email" | mailx -s "Subject" -a "Attachment" me@email.com
关键说明
  • 自动日志重定向:exec &> "${LOG_FILE}"会将脚本后续所有命令的标准输出(stdout)和标准错误(stderr)都写入指定日志文件,包括set -x的调试信息、Hive的Map/Reduce运行日志,完全屏蔽控制台输出。
  • 日期变量修正:原脚本中tday的date -d "$date"是错误写法,直接用date +"%m_%d_%Y"即可生成当前日期的指定格式。
  • 拼写错误修正:修复了原脚本中的ehco→echo、Attchement→Attachment、-me@email.com→me@email.com(mailx收件人参数无需前缀-)。

内容的提问来源于stack exchange,提问作者Sotark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 12:10:37