Can we access shell variables from Julia?

shell

#1

I may be missing something but would it be possible to use $ (or appropriate symbol) in a Cmd object in the “shell sense” as opposed to the julia interpolation sense? As a slightly stupid example:

run(`echo $PWD`)

would return the path. Of course that would be useless and pwd() is the obvious choice but it’s just an analogy. Executing the snippet above gives an error because PWD is not defined in the environment. Escaping the $ sign with single quotes or \ just shows "$PWD". Is it by design that we can’t use $ in another way than the string interpolation?


#2
julia> run(`echo $(ENV["PWD"])`)
/home/tbesard

#4

Cool yes that works and answers the question, thanks!

Unfortunately, one of the commands I’m trying to run is echo $! (last process) which is not in ENV. I ended up finding a workaround using a pipeline with a bunch of greps though, but it’s a bit of a hack…


#5

Because $! is a special variable as implemented by your shell, which isn’t used by run (see docs, “The command is never run with a shell”). You can use it if you explicitly launch a shell:

julia> run(`bash -c "echo & echo \$!"`)
4185

#6

very useful, thanks!