Interpolating an empty string inside backticks

Today I was a surprised by by this be this behavior

a="-la"
p=`ls $a`

results in p equal ls -la which is expected.

However,

a=""
p=`ls $a`

results in p equal ls ''. The two single quote marks are a bit strange here. I am trying to something where I check for certain conditions and pass and optional argument to an external program.

I fail to see the point of this peculiar interpolation inside backticks.

We do not parse the string you try to interpolate since that’s the source of all sorts of bugs. It’s also not possible to interpolate empty string argument otherwise. If you want optional argument, interpolate `-la` or `` instead.

2 Likes

This is an important pattern: if you’re building up a command in parts, use command syntax for the parts as well – that will work correctly. Use strings for, well, strings – like names of things or parts of names of things.

6 Likes

2 posts were split to a new topic: Using * as a wildcard in backtick commands