10

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?

Jolta
  • 2,620
  • 1
  • 29
  • 42
Luca Borrione
  • 16,324
  • 8
  • 52
  • 66

1 Answers1

15

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.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Luca Borrione
  • 16,324
  • 8
  • 52
  • 66