How to interpolate into the `julia -c` shell command

I have a bit of julia code in a shell variable. I want to execute it.

When I run this script

code='import Pkg'
echo $code
julia -e $code
echo pass

I get this

import Pkg
ERROR: syntax: incomplete: premature end of input
Stacktrace:
 [1] top-level scope
   @ none:1

When I try to quote the code

code=\''import Pkg'\'
echo $code
julia -e $code
echo pass

I get this

'import Pkg'
ERROR: syntax: incomplete: invalid character literal
Stacktrace:
 [1] top-level scope
   @ none:1

How can I run the code in an environment variable using julia -c [???]

This issue is that the shell is splitting 'import Pkg' by space delimiter, so the equivalent of julia -e 'import is being executed, hence the incomplete: premature end of input error.
You can control the splitting using the IFS shell variable (aka Internal Field Separator or Input Field Separator). This can be redefined as, say, just a new line character. So wrapping the julia invocation might be the answer here:

(IFS=$'\n'; julia -e $code)
1 Like

The standard solution is to quote variables (which you should always do anyway), not to hack IFS:

julia -e "${code}"
4 Likes

That’s a better way of doing it!