Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can a sourced file inherit trap DEBUG?

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?

like image 540
Luca Borrione Avatar asked Nov 04 '12 21:11

Luca Borrione


1 Answers

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.

like image 156
Luca Borrione Avatar answered Sep 22 '22 21:09

Luca Borrione