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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Most excellent! I just knew there had to be a more elegant way. Thanks, Kevin; this will go into immediate use...
can it also output to current terminal and log to a file? I tried to use tee with exec but found no way..
I would like to link to this question where it is possible to see the output and also log it, all commanded from within the script!
2

maybe you are looking for set -x?

1 Comment

@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.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.