I'm trying to display an error message along with the call stack from a function that receives an error message. I thought using the FUNCNAME array would work, but I've noticed it has 20 values, with some of them being empty. Because of this, I can't determine the main script filename correctly using the length of FUNCNAME. I know it's possible to find the last non-empty index, but I'm curious about the reason behind those empty values in the FUNCNAME array. Any insights would be greatly appreciated!
3 Answers
I think what's weird here is that typically FUNCNAME shouldn't have empty elements. Have you tried running a minimal viable script to reproduce the issue? It could help you spot if it's something specific to your setup. If you're relying on nested function calls, that might be where the empty values come from. Just dump the current state of FUNCNAME before your function calls to see if the empties occur at a specific point.
Awesome that you're exploring that! A sample script always helps to clarify what's going on, especially with nested functions.
It sounds like the call stack could be getting modified somewhere, which might lead to empty elements in FUNCNAME. Can't directly assign to it, but you can unset specific elements. For example, unsetting an element will shift the rest, which might produce some odd behavior. You could try something like this to see if it resolves the issue:
```bash
$ a() { declare -p FUNCNAME; }
$ b() { unset FUNCNAME[1]; a; }
$ c() { b; }
$ d() { c; }
$ d
```
Keep an eye on how you're calling the functions to see if something is unsetting or not updating properly!
Interesting! So that would mean you're possibly dealing with a side effect from nesting functions? I think running similar tests could help expose if there's something unexpectedly affecting FUNCNAME.
Right, capturing the way you manipulate the array could shine a light on what's happening. Just keep testing out different configurations!
That's definitely unusual. If you can share a sample code snippet, that could be great for diagnosing this. My tests with simple function calls show no empty elements in FUNCNAME, which suggests it might be an edge case in your deeper script. Let me know if you can replicate it with something simpler!
I had a similar issue recently, and it turned out to be a stray unset command in the wrong spot—definitely worth double-checking.
I actually have a simple test case that I shared in another reply. It happens when I run certain nested functions.
I shared a min script with another user showing where the empties pop up. I'm running on openSuse via WSL2.