Running the following snippet:
#!/bin/bash
function preexec ()
{
echo -e "\n-->preexec command: $BASH_COMMAND"
}
trap 'preexec' DEBUG
function testfunc ()
{
echo "testfunc called $1"
}
testfunc "main"
source "source.sh"
exit 0
where source.sh is
#!/bin/bash
testfunc "source"
gives:
-->preexec command: testfunc "main"
testfunc called main
-->preexec command: source "source.sh"
testfunc called source
-->preexec command: exit 0
which means that every commands inside the sourced file are not trapped by the DEBUG trap.
In fact if I add the line
trap 'preexec' DEBUG
inside source.sh as second line, everything works as wanted (commands inside source file are trapped too).
How can I make this a default behaviour in order to avoid repeating the above line for any file I need to source?
In other words: is there any chance to tell the sourced file to inherit the DEBUG trap?
I solved setting in the main file:
set -o functrace
From BASH man:
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.
Being 'source' a shell function, they are inherited.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With