I created a func.sh script file containing:
1. function testfunc () 2. { 3. echo "--> TESTFUNC CALLED" 4. caller 0 5. 6.
Then I made main.sh script
1. #!/bin/bash 2. 3. source 'func.sh' 4. testfunc 5. 6. exit 0
My goal is to catch lineno 4 (in the above script), where I was not able to correctly return the return value.
For this, I tried:
1. #!/bin/bash 2. 3. set -o errexit 4. 5. function exit_handler () 6. { 7. echo "--> EXIT HANDLER" 8. 9. echo "BACKTRACE IS:" 10. local i=0 11. while caller $i > /dev/null 12. do 13. caller $i 14. let "i=i+1" 15. done 16. 17. echo "PASSED LINENO IS: $1" 18. exit 0 19. } 20. trap 'exit_handler $LINENO' EXIT 21. 22. source 'func.sh' 23. testfunc 24. 25. exit 0
Here I would like to catch lineno 23 .
Output:
--> TESTFUNC CALLED 23 main import.sh now I return a non-zero value --> EXIT HANDLER BACKTRACE IS: 1 main.sh PASSED LINENO IS: 1
The correct lineno is detected by the caller inside the function itself, but not in the trap where the correct script name (main.sh) is, but not lineno (1 ??? instead of 22)
I also tried
1. #!/bin/bash 2. 3. function err_handler () 4. { 5. echo "--> ERR HANDLER" 6. 7. echo "BACKTRACE IS:" 8. local i=0 9. while caller $i > /dev/null 10. do 11. caller $i 12. let "i=i+1" 13. done 14. 15. echo "PASSED LINENO IS: $1" 16. exit 0 17. } 18. trap 'err_handler $LINENO' ERR 19. 20. source 'func.sh' 21. testfunc 22. 23. exit 0
but conclusion:
--> TESTFUNC CALLED 21 main import.sh now I return a non-zero value --> ERR HANDLER BACKTRACE IS: 8 main.sh PASSED LINENO IS: 8
The caller inside the function itself still detects the correct lineno (21 in this case), but the situation inside the trap is even worse because it gets lineno 8, which is the line inside func.sh where there is a return of 1 ... (at that time as the caller inside the trap refers to the line with the wrong script main.sh).
At the moment, I'm out of ideas ...