我有一些关键的 bash 脚本被我无法控制的代码调用,而且我看不到它们的控制台输出。我想要完整跟踪这些脚本的作用以供以后分析。为此,我想让每个脚本都进行 self 跟踪。这是我目前正在做的事情:
#!/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...
有没有更好、更简洁的方法来做到这一点?
最佳答案
#!/bin/bash
exec >>log_file 2>&1
echo Hello world
date
exec
有一个关于重定向的神奇行为:“如果 command 没有指定,任何重定向都在当前 shell 中生效,返回状态为 0。如果有是重定向错误,返回状态为1。”
此外,关于您的原始解决方案,exec "$0"
优于 "$0"; exit $?
,因为前者在子进程退出之前不会留下额外的 shell 进程。
关于bash - 使 bash 脚本自跟踪的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2439948/