Recently I wanted to know the best way to get the path to the currently running script/file in Bash.
I found a lot of answers. In particular one was:
"${BASH_SOURCE:-${(%):-%x}}"
I remember deciding at the time that this was the best solution for my needs. Now I'm trying to remember why. I know what some of the pieces mean, but not all. And even with what I do know I can't put it all together to make any sense of it. It works. But why?
Every effort I've made to find this specific code anywhere on the web (including searching for bits of it) has failed, so I can't find where I found it originally.
Can anyone tell me what each piece means (and perhaps even suggest why I might have chosen this over other answers)?
Thanks!
UPDATE next day: great answer (and comments) from @rici which explain everything, including why I chose it.
It seems I chose this entire expression to enable the sourced files I'm using it in to be used reliably in both bash and zsh - which was and is a goal. With the dual substitutions, the entire expression gets the same answer in either shell.
Explains why I couldn't make any sense of (or find anything sensible via google for) the ${(%):-%x} part in bash because... well... it doesn't make much sense in bash, lol, since it's for zsh. I'm now adding a zsh tag to this for that reason.
Second UPDATE an hour later, in case this helps anyone: I've now tracked down this:
${BASH_SOURCE[0]} equivalent in zsh?
... which is where I got the ${(%):-%x}
from originally, most notably this specific answer: