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

Kev*_*tle 8 bash logging trace

我有一些关键的bash脚本,由我无法控制的代码调用,我无法看到他们的控制台输出.我想要完整地了解这些脚本的作用,以便以后分析.为此,我想让每个脚本都自我跟踪.这是我目前正在做的事情:

#!/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...
Run Code Online (Sandbox Code Playgroud)

有更好,更清洁的方法吗?

Kev*_*eid 13

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

echo Hello world
date
Run Code Online (Sandbox Code Playgroud)

exec有关重定向的神奇行为:"如果未指定命令,则任何重定向在当前shell中生效,返回状态为0.如果存在重定向错误,则返回状态为1."

此外,关于您的原始解决方案,exec "$0"最好是"$0"; exit $?,因为前者不会留下额外的shell进程,直到子进程退出.