2

I am trying to debug a bash function.

Is it possible to print all the commands executed by a bash function? I know that it is possible to print all the commands by a bash script by changing

#!/bin/bash

to

#!/bin/bash -x

How do I get the same effect for a bash function?

Thank you.

1 Answer 1

4

You need to edit the function to add and remove tracing, eg:-

FuncName()
{
    set -x ;# Enable tracing on entry

    ... (function code) ...

    set +x ;# Disable tracing on exit
}
2
  • Thank you. I found out that set +x is not required at the end if there is only 1 function being executed. The set -x in the function doesn't affect the shell.
    – user674669
    Commented Dec 11, 2018 at 20:06
  • 1
    My findings are different, but I don't know the environment from which you are calling the function. Functions run in the current shell, and any changes to environment variables, options and the current directory are retained when the function returns. If you are calling a function within a script, then such changes are maintained within the calling script, but lost when the script returns. If you define a function in the current shell and call it from there, its environment changes will be maintained on exit, hence set +x.
    – AFH
    Commented Dec 11, 2018 at 21:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .