How can I interpolate inside single quotes inside a command?

How can I interpolate inside single quotes inside a command?

h = "hey"
`echo $h` # this works
`echo '$h'` # this does not

Note that the original poster on Slack cannot see your response here on Discourse. Consider transcribing the appropriate answer back to Slack, or pinging the poster here on Discourse so they can follow this thread.
(Original message :slack:) (More Info)

Answering my own question
I wanted this command

julia> run(```WolframKernel -run 'Print["$h"];Exit[];'```)
Mathematica 12.2.0 Kernel for Linux x86 (64-bit)
Copyright 1988-2020 Wolfram Research, Inc.
$h
Process(`WolframKernel -run 'Print["$h"];Exit[];'`, ProcessExited(0))

to output this

julia> run(```WolframKernel -run 'Print["$h"];Exit[];'```)
Mathematica 12.2.0 Kernel for Linux x86 (64-bit)
Copyright 1988-2020 Wolfram Research, Inc.
hey
Process(`WolframKernel -run 'Print["$h"];Exit[];'`, ProcessExited(0))

This can be done by prefacing the double quotes with \"

julia> run(```WolframKernel -run "Print[\"$h\"];Exit[];"```)
Mathematica 12.2.0 Kernel for Linux x86 (64-bit)
Copyright 1988-2020 Wolfram Research, Inc.
hey
Process(`WolframKernel -run 'Print["hey"];Exit[];'`, ProcessExited(0))

Hat tip to @simeonschaub.

1 Like

I would really advise against ever trying to tie yourself in knots with literal quotes inside Cmds. The whole point of them is to avoid ever using quotes in the first place. If you want to pass a string to an external command, well, first create the string:

julia> h = "hey"
"hey"

julia> str = """Print["$h"];Exit[];"""
"Print[\"hey\"];Exit[];"

julia> `WolframKernel -run $str`
`WolframKernel -run 'Print["hey"];Exit[];'`

The Cmd object will actually pretty-print the object with underlines to underscore each independent argument that’s getting passed — and it even prints as though it were quoted for you:

image

8 Likes

Thanks a lot @mbauman, that does seem quite a bit more sensible. I found a work around for my needs, but this is still useful.