Search code examples
javascriptnode.jsbashshelltemplate-strings

Proper way to escape ${} in a JS template string


I am creating a bash command:

const k = cp.spawn('bash');

k.stdin.end(`
  alias ssh='ssh "${SSH_ARGS[@]}"'
`);

but of course, I have to escape it. I assume the best way to escape it, is using:

 `alias ssh='ssh "\${SSH_ARGS[@]}"'`

can anyone explain why that works?


Solution

  • Escaping just the $ works for the same reasons that ordinary curly braces don't throw errors — an expression within a template string is identified by ${ at the beginning and } at the end. If the dollar sign is escaped, it isn't interpreted as part of the ${ keyword, and the curly braces are interpreted as normal characters.