For years I’ve been frustrated by my inablity to puzzle out how to write this in bash:
H=$(dirname $0)
so it’s safe if $0 has spaces in it.
Clearly
H="$(dirname $0)"
is better, but still the $0 isn’t usefully quoted.
I finally complained to the shellcheck author that this should be in the FAQ, though there isn’t a FAQ. And he assured me if you do it right it isn’t a problem. He also happened to mention the answer:
H="$(dirname "$0")"
I complained that just because it wasn’t a question if you’d ask if you knew the answer didn’t mean that it wasn’t a commonly asked question. So he added (or updated) a wiki page to say that the $(…) creates a new “context”.
So there you go.
Wow, yeah, I struggle with quote escaping a lot — does this single-quote need to be escaped, what about these nested double-quote — and that is not at all obvious. I suppose ‘context’ is a decent term for this, but I fail fast at keeping a stack of context in my head. Command redirection might be apropos, given that pipes are easier to reason about.