6
votes

I'm trying to run a shell command from Julia which needs to have an environment variable set to some specific value. I have two problems:

  1. How to set environment variables to be used by Julia's
    run(command, args...; wait::Bool = true) command?

  2. How to pass special sign $ to this process without interpolating it? I want to test if the variable is available for my program.

What I have done so far:

Let's say I want to define an environment variable FOO=bar and check if it's accessible within the shell with shell command echo $FOO.

To prevent Julia interpolating $ I already quoted it like explained in the official documentation but then echo is printing $PATH and not its value.

So for FOO I got the following output

julia> run(`echo '$FOO'`)
$FOO
Process(`echo '$FOO'`, ProcessExited(0))

but would have expected something like

julia> run(`echo '$FOO'`)

Process(`echo '$FOO'`, ProcessExited(0))

if FOO is undefined or

julia> run(`echo '$FOO'`)
bar
Process(`echo '$FOO'`, ProcessExited(0))

if the value is set to bar.

2
Could you clarify what you mean by "but then the shell is not doing what I expected"? What is it doing? What did you expect it to do? See how to ask a good question and how to create a minimal, reproducible example. - Engineero
I would have expected to get the actual value of PATH, so something like /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin. I edited my question accordingly. - AnHeuermann
Also to keep it more consistent I changed my example to FOO - AnHeuermann
See my answer. It shows how you are supposed to do this in Julia, including links to the documentation. If it works for you, please mark it as accepted :) - Engineero

2 Answers

1
votes

Check out the Julia documentation on environment variables. You can set an environment variable with:

julia> ENV["FOO"] = "bar"
"bar"

and you can retrieve the value of an environment variable with:

julia> ENV["FOO"]
"bar"
julia> ENV["PATH"]
"really long string of my path"

As you've already stated, you can avoid interpreting the $ by single-quoting that part of your run command. I'm not totally sure what you are looking for there.

0
votes

Not elegant, but this works:

julia> write("temp.sh", "echo foo=\$BAR");

julia> run(`bash temp.sh`)
foo=
Process(`bash temp.sh`, ProcessExited(0))

julia> ENV["BAR"] = "bar";

julia> run(`bash temp.sh`)
foo=bar
Process(`bash temp.sh`, ProcessExited(0))

I guess Julia injects the content of ENV into the shell before running the command. And that's all I needed to know as I'll be launching other executables which require some environment variables to be set. So when setting them inside ENV[], they will be available to the executables you run from within that Julia session.