Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash: debug option and functions

If I run

bash -x myscript.sh

I'll get debugging output.

But if I have a function in myscript.sh, the code in the function is immune to -x option. It writes to output only the name of the function.

How to obtain debugging output for functions in bash scripts?

Update:

Following the ztank1013's response, I just realized that I used ksh, not bash. Seems bash has by default the functrace option enabled in my system(thanks bash-o-logist)

I am satisfied, but for the community I maintain the question open for ksh.

For script:

#!/bin/ksh

a=2
testering(){
        a=3
        if [ $a -eq 3 ]; then
                echo lili
        fi
}
if [ $a -eq 2 ]; then
        echo mimi
fi

testering
exit

output of ksh -x ./testdebug.sh is:

+ a=2
+ [ 2 -eq 2 ]
+ echo mimi
mimi
+ testering
lili
+ exit

So, for ksh, what's the trick?

(If no answer will come, the 'correct' will go to bash-o-logist.)

like image 851
Florin stands with Ukraine Avatar asked Sep 14 '11 11:09

Florin stands with Ukraine


2 Answers

With bash, you can use functrace option in your script

set -o functrace

See manpage for bash for other debugger options.

like image 168
bash-o-logist Avatar answered Oct 04 '22 05:10

bash-o-logist


I cannot reproduce your problem, in fact given my test script (debug.sh):

[root ~]# cat debug.sh
#!/bin/bash
fun01 () {
echo "BUT HERE I am inside the function fun01() body"
}
echo "HERE I am outside the function fun01() body!"
sleep 2
fun01
exit

I run it with debug option turned off:

[root ~]# ./debug.sh
HERE I am outside the function fun01() body!
BUT HERE I am inside the function fun01() body

and turned on (bash -x ...):

[root ~]# bash -x ./debug.sh
+ echo 'HERE I am outside the function fun01() body!'
HERE I am outside the function fun01() body!
+ sleep 2
+ fun01
+ echo 'BUT HERE I am inside the function fun01() body'
BUT HERE I am inside the function fun01() body
+ exit

As far as I can see the line executed inside the fun01() function is showed with a starting + which is the debugger in action.

@bash-o-logist Even if I add variable or if/then/else conditional constructs I still get all the debug info:

[root@ ~]# cat debug-new.sh
#!/bin/bash
fun01 () {
INSIDEVAR='Never really use this one'
echo "BUT HERE I am inside the function fun01() body"
if [ true ] ; then echo 'this is going to be printed always!' ; fi
}
echo "HERE I am outside the function fun01() body!"
sleep 2
fun01
exit

Executing again:

[root@ ~]# bash -x debug-new.sh
+ echo 'HERE I am outside the function fun01() body!'
HERE I am outside the function fun01() body!
+ sleep 2
+ fun01
+ INSIDEVAR='Never really use this one'
+ echo 'BUT HERE I am inside the function fun01() body'
BUT HERE I am inside the function fun01() body
+ '[' true ']'
+ echo 'this is going to be printed always!'
this is going to be printed always!
+ exit
like image 21
ztank1013 Avatar answered Oct 04 '22 07:10

ztank1013