Search code examples
bashfunctionverbose

is there a clean, concise way to push/pop bash verbose and xtrace options for a funtion?


(Linux bash 4.1.2) I have a bash function calling another function. The low level function wants to have -xv set for debugging, but I don't want it to mess with the values of x and v in the parent function. I.e. I want the child function to push -xv, then restore the previous setting on return. E.g.:

function outer(){ echo starting; inner; echo done; }
function inner(){
    set -xv
    echo inside
    set +xv
  }
outer

This works if the setting in outer is default; otherwise it forces +xv in the rest of outer's code. I can imagine some very messy script that parses BASHOPTS, but it seems like there should be a better way?


Solution

  • If you don't need to share the outside code's environment or modify variables from outside within inside, you can launch a subprocess with ( inner )

    function outer(){ echo starting; inner; echo done; }
    function inner(){
        (
            set -xv
            echo inside
        )
    }
    outer
    

    Note that since you are executing in a subshell, you don't need to unset the x and v.

    You can also simply wrap the call to inner in outer without modifying inner:

    function outer(){ echo starting; ( inner ); echo done; }
    

    You can find more information here about subshells and variable scopes. https://www.tldp.org/LDP/abs/html/subshells.html