简体   繁体   English

使bash脚本自我跟踪的更好方法是什么?

[英]Better way to make a bash script self-tracing?

I have certain critical bash scripts that are invoked by code I don't control, and where I can't see their console output. 我有一些关键的bash脚本,由我无法控制的代码调用,我无法看到他们的控制台输出。 I want a complete trace of what these scripts did for later analysis. 我想要完整地了解这些脚本的作用,以便以后分析。 To do this I want to make each script self-tracing. 为此,我想让每个脚本都自我跟踪。 Here is what I am currently doing: 这是我目前正在做的事情:

#!/bin/bash
# if last arg is not '_worker_', relaunch with stdout and stderr
# redirected to my log file...
if [[ "$BASH_ARGV" != "_worker_" ]]; then
    $0 "$@" _worker_ >>/some_log_file 2>&1  # add tee if console output wanted
    exit $?
fi
# rest of script follows...

Is there a better, cleaner way to do this? 有更好,更清洁的方法吗?

#!/bin/bash
exec >>log_file 2>&1

echo Hello world
date

exec has a magic behavior regarding redirections: “If command is not specified, any redirections take effect in the current shell, and the return status is 0. If there is a redirection error, the return status is 1.” exec有关于重定向的神奇行为:“如果未指定命令 ,则任何重定向在当前shell中生效,返回状态为0.如果存在重定向错误,则返回状态为1.”

Also, regarding your original solution, exec "$0" is better than "$0"; exit $? 此外,关于您的原始解决方案, exec "$0"优于"$0"; exit $? "$0"; exit $? , because the former doesn't leave an extra shell process around until the subprocess exits. ,因为前者在子进程退出之前不会留下额外的shell进程。

也许你正在寻找set -x

you may check a common open source trace library with support for bash. 您可以检查支持bash的常见开源跟踪库。

The current available component is for scripting by bash, soon available are Python and C++. 当前可用的组件是由bash编写的脚本,很快就可以使用Python和C ++。 Additional going to follow are: Ruby, Java, JavaScript, SQL, PowerShell,... 另外还有:Ruby,Java,JavaScript,SQL,PowerShell,......

The license is Apache-2.0 许可证是Apache-2.0

WKR Arno-Can Uestuensoez WKR Arno-Can Uestuensoez

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM