bash将set -x的输出存储到日志文件 [英] bash storing the output of set -x to log file

查看:730
本文介绍了bash将set -x的输出存储到日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的下载脚本,并且使用set -x效果很好; 我可以看到它执行的每个步骤,并且可以确定脚本中的错误 或在下载中:

I have a simple download script and I use set -x which works great; I can see each step it performs, and I can identify errors in the script or in the download:

#!/bin/bash
set -x
#short_date=$(/bin/date +%m%d%y)
short_date=$(/bin/date -d "8 day ago" +%m%d%y)
#long_date=$(/bin/date +%Y%m%d)
long_date=$(/bin/date -d "8 day ago" +%Y%m%d)
scp -v -P 1332 -i /home/casper/.ssh/id_rsa_BANK friendly@192.168.1.10:/home/friendly/transfer/out/EXCHANGE_$short_date.csv /local/casper3/dailymetrics/BANK_$long_date.csv

我想使这项工作自动化.有什么方法可以将set -x输出保存到日志文件吗?也许到一个日志文件-或每天不同的日志文件.我不知道哪种方法最有效.

I would like to automate this job. Is there a way I could save the set -x output to a log file? Maybe to one log file - or a different log file for each day. I don't know what would work best.

下面是上述脚本的示例输出set -x.

Below is sample set -x output from the above script.

++ /bin/date +%m%d%y
+ short_date=102814
++ /bin/date +%Y%m%d
+ long_date=20141028
+ scp -v -P 1332 -i /home/casper/.ssh/id_rsa_BANK friendly@192.168.1.10:/home/friendly/transfer/out/EXCHANGE_102814.csv /local/casper3/dailymetrics/BANK_20141028.csv
Executing: program /usr/bin/ssh host 192.168.1.10, user friendly, command scp -v -f /home/friendly/transfer/out/EXCHANGE_102814.csv
OpenSSH_5.3p1, OpenSSL 1.0.0-fips 29 Mar 2010
debug1: Reading configuration data /home/casper/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to 192.168.1.10 [192.168.1.10] port 7777.
debug1: Connection established.

推荐答案

假定bash 4,可以将BASH_XTRACEFD设置为覆盖写入set -x输出的文件描述符(默认情况下为2,stderr):

Assuming bash 4, BASH_XTRACEFD can be set to override the file descriptor (by default 2, stderr) to which set -x output is written:

short_date=$(/bin/date +%m%d%y)
exec {BASH_XTRACEFD}>>"$short_date".log
set -x

如果运行bash 4.0而不是4.1或更高版本,则具有BASH_XTRACEFD,但没有自动文件描述符分配,这意味着您需要自己分配一个;在下面的示例中,我选择文件描述符100:

If running bash 4.0 rather than 4.1 or newer, you have BASH_XTRACEFD but not automatic file descriptor allocation, meaning you'll need to assign one yourself; in the below example, I'm picking file descriptor 100:

short_date=$(/bin/date +%m%d%y)
exec 100>>"$short_date".log
BASH_XTRACEFD=100
set -x

对于较早的版本,唯一的选择是重定向所有stderr,而不是仅重定向xtrace流:

For older releases, your only choice is to redirect all of stderr, rather than only the xtrace stream:

short_date=$(/bin/date +%m%d%y)
exec 2>>"$short_date.log"
set -x

这篇关于bash将set -x的输出存储到日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆