Disclaimer

The content of this blog is my personal opinion only. Although I am an employee - currently of Nvidia, in the past of other companies such as Iagination Technologies, MIPS, Intellectual Ventures, Intel, AMD, Motorola, and Gould - I reveal this only so that the reader may account for any possible bias I may have towards my employer's products. The statements I make here in no way represent my employer's position, nor am I authorized to speak on behalf of my employer. In fact, this posting may not even represent my personal opinion, since occasionally I play devil's advocate.

See http://docs.google.com/View?id=dcxddbtr_23cg5thdfj for photo credits.

Friday, October 28, 2016

Bash trap DEBUG does not work inside shell functions - not even to print

Bash Reference Manual:
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. Refer to the description of the extdebug option to the shopt builtin (see The Shopt Builtin) for details of its effect on the DEBUG trap.


'via Blog this'
This bit me today:



It seems that



  • not only does the bash DEBUG trap not run for commands inside shell functions, but only once at the start
    • which is not unreasonable as a default
    • especially if shopt extdebug allowed you to "trap DEBUG into" shell functions (which I have so far not been able to make work)
  • but "trap ... DEBUG" is actually disabled inside shell functions
    • which means that you cannot have a shell function that formats the current trap status nicely
    • or which tries to add a "trap ... DEBUG" handler to its caller


Unless I can get shopt extdebug to work as advertised - well, at least, as I tyhinik it is advertised - there is a loss of abstraction.



Kluge: pass in the old trap handler setup, compute new, apply outside function.



:-(





A shell session.





    Mac: trap

    trap -- 'shell_session_update' EXIT



It looks like Apple sets up a trap handler by default.



    Mac: trap 'echo DEBUG' DEBUG

    DEBUG



Setting up a trivial (but annoying) DEBUG trap handler.

Run once before any command is run.



    Mac:

    DEBUG



Or even when ENTER is pressed to get a new prompt





    Mac: echo xx

    DEBUG

    xx

    DEBUG



Run twice as set up above, once for the command,

once for the exit handler





Now trying to run trap in a function



    Mac: trap

    DEBUG

    trap -- 'shell_session_update' EXIT

    trap -- 'echo DEBUG' DEBUG

    DEBUG



    Mac: foo() {

    > trap

    > }

    DEBUG



    Mac: foo

    DEBUG

    trap -- 'shell_session_update' EXIT

    DEBUG



The shell function can execute the trap builtin

but the trap DEBUG handler was disabled