Reputation: 5714
I developed a tool in bash. I have a function created with some debug purposes. Let's suppose:
function my_debug_stuff() {
echo "it is debugging"
}
Of course is not as simple as this, but this is enough for the example. Ok, after creating this, I'm calling that function from every function in my bash tool:
#!/bin/bash
function my_debug_stuff() {
echo "it is debugging"
}
function first() {
my_debug_stuff
echo "doing some first stuff"
}
function second() {
my_debug_stuff
echo "doing some second stuff"
}
function main() {
first
second
echo "doing main stuff"
}
I'm calling to my_debug_stuff function on every function in the bash tool except in the main function. Is there a more elegant way to do this? any bash "trick"? or repeating the call to my_debug_stuff function is correct? I'd like to know if I can save lines or repeated stuff.
Upvotes: 1
Views: 101
Reputation: 3041
The approach you are using is fine. Here are a couple of alternatives you could look at, which may or may not be more appropriate for you situation.
Using the debug trap is one way that at least works for your toy example. From the man
section for trap
:
If a sigspec is DEBUG, the command arg is executed before every simple command, for command, case command, select command, every arithmetic for command, and before the first command executes in a shell function.
So the following would work for the example you give:
#!/bin/bash
function my_debug_stuff() {
echo "it is debugging"
}
function first() {
echo "doing some first stuff"
}
function second() {
echo "doing some second stuff"
}
trap my_debug_stuff DEBUG
first
second
echo "doing main stuff"
Of course the debug trap would also be called in all the other cases mentioned above, so I doubt how useful it will be for your real script. Probably worth a mention though. The effect of set -T
may also have some use:
If set, any traps on DEBUG and RETURN are inherited by shell functions, command substitutions, and commands executed in a subshell environment. The DEBUG and RETURN traps are normally not inherited in such cases.
Alternatively, you could try passing your other functions as an argument to your debug function.
#!/bin/bash
function debug() {
echo "it is debugging"
"$@"
}
function first() {
echo "doing some first stuff"
}
function second() {
echo "doing some second stuff"
}
debug first
debug second
echo "doing main stuff"
Again, not necessarily a better approach but may be preferable depending on the specifics of your real code.
Upvotes: 2