使用 set -x 时重定向 bash 脚本中的所有输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11229385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
redirect all output in a bash script when using set -x
提问by Thanos
I have a bash script that has set -x
in it. Is it possible to redirect the debug prints of this script and all its output to a file? Ideally I would like to do something like this:
我有一个 bash 脚本set -x
。是否可以将此脚本的调试打印及其所有输出重定向到文件?理想情况下,我想做这样的事情:
#!/bin/bash
set -x
(some magic command here...) > /tmp/mylog
echo "test"
and get the
并得到
+ echo test
test
output in /tmp/mylog, not in stdout.
在 /tmp/mylog 中输出,而不是在 stdout 中。
回答by bcelary
This is what I've just googled and I remember myself using this some time ago...
这是我刚刚在谷歌上搜索的内容,我记得我前段时间使用过这个......
Use exec to redirect both standard output and standard error of all commands in a script:
使用 exec 重定向脚本中所有命令的标准输出和标准错误:
#!/bin/bash
logfile=$$.log
exec > $logfile 2>&1
For more redirection magic check out Advanced Bash Scripting Guide - I/O Redirection.
有关更多重定向魔术,请查看高级 Bash 脚本指南 - I/O 重定向。
If you also want to see the output and debug on the terminal in additionto in the log file, see redirect COPY of stdout to log file from within bash script itself.
如果除了日志文件之外,您还想在终端上查看输出和调试,请参阅将 stdout 的 COPY 重定向到 bash 脚本本身中的日志文件。
If you want to handle the destination of the set -x
trace output independently of normal STDOUT
and STDERR
, see bash storing the output of set -x to log file.
如果要set -x
独立于 normal STDOUT
and处理跟踪输出的目标STDERR
,请参阅bash 将 set -x 的输出存储到日志文件。
回答by Petesh
the -x
output goes to stderr, so to log it do:
在-x
输出为标准错误,所以要记录它做的事:
set -x
exec 2>/tmp/mylog
回答by calamari
In my case, the script was being called multiple times from elsewhere, and I wasn't seeing everything, so I did an append instead, and it worked:
就我而言,脚本从其他地方被多次调用,我没有看到所有内容,所以我做了一个附加,并且它起作用了:
exec 1>>FILENAME 2>&1
set -x
To avoid confusion, be sure to delete FILENAME before each run.
为避免混淆,请务必在每次运行前删除 FILENAME。
回答by PALEN
To redirect stderrand stdout:
重定向stderr和stdout:
exec &>> $LOG_FILE_NAME
If you want to append to file. To overwrite file:
如果你想附加到文件。覆盖文件:
exec &> $LOG_FILE_NAME