8

I have certain critical bash scripts that are invoked by code I don't control, and where I can't see their console output. 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?

Kevin Little
  • 12,436
  • 5
  • 39
  • 47

3 Answers3

13
#!/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.”

Also, regarding your original solution, exec "$0" is better than "$0"; exit $?, because the former doesn't leave an extra shell process around until the subprocess exits.

Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
  • Most excellent! I just knew there had to be a more elegant way. Thanks, Kevin; this will go into immediate use... – Kevin Little Mar 13 '10 at 23:46
  • 1
    can it also output to current terminal and log to a file? I tried to use `tee` with `exec` but found no way.. – Aquarius Power Oct 30 '13 at 16:08
  • 1
    I would like to link to [this question](http://stackoverflow.com/questions/3173131/redirect-copy-of-stdout-to-log-file-from-within-bash-script-itself) where it is possible to see the output and also log it, all commanded from within the script! – Aquarius Power Oct 30 '13 at 16:30
2

maybe you are looking for set -x?

Anycorn
  • 50,217
  • 42
  • 167
  • 261
  • @aaa: Yep, I know about "set -x" -- that's one of the things I occasionally make use of in the "# rest of script follows..." section above. I should have mentioned it; thanks for doing so. – Kevin Little Mar 13 '10 at 23:38
0

you may check a common open source trace library with support for bash.

The current available component is for scripting by bash, soon available are Python and C++. Additional going to follow are: Ruby, Java, JavaScript, SQL, PowerShell,...

The license is Apache-2.0

WKR Arno-Can Uestuensoez

acue
  • 381
  • 3
  • 6