How can Julia shell commands set environment variables?

Viewed 486

When I try to set an environment variable in a shell command in the REPL like this:

;SOME_ENV="foo" some_command

I get an error:

zsh:1: command not found: SOME_ENV=foo

How can I set environment variables for individual commands?

1 Answers

One solution is to use withenv():

julia> withenv("SOME_ENV"=>"foo") do
           run(`some_command`)
       end

Alternatively, you could use setenv(), but it completely replaces the environment, instead of just modifying it like withenv() does. In particular, you lose the PATH environment variable, so you need to specify the full path of the command:

julia> run(setenv(`/path/to/some_command`, "FOO"=>"BAR"))

Or you can copy the PATH variable into the new environment:

julia> run(setenv(`some_command`, "FOO"=>"BAR", "PATH"=>ENV["PATH"]))

For more details, see the documentation for withenv() and setenv().

Related