"Sourcing" a script's env into D?

Steven Schveighoffer schveiguy at yahoo.com
Thu Sep 29 13:09:59 PDT 2011


On Thu, 29 Sep 2011 13:31:13 -0400, Nick Sabalausky <a at a.a> wrote:

> Due to process separation, the following won't work:
>
> script.sh:
> #!/bin/sh
> SOME_VAR=foobar
>
> test.d:
> import std.process;
> void main()
> {
>     system("./script.sh");
>     assert(environment["SOME_VAR"] == "foobar");
> }
>
> This, of course, is because the script is run in a totally separate  
> process
> (AIUI). The same thing happens in Windows, too.
>
> Is there some way to actually get the env that results from the script?  
> I'm
> looking for solutions for both Posix and Windows.

No.  The way it works when you "source" a script from another script is it  
uses the same process to interpret the script file, which sets the  
environment up.

Since a D program cannot interpret shell script, all you can do is read  
the environment from the script (have it output the environment) and read  
it in:

#!/bin/sh
SOME_VAR=foobar
# note this is needed for SOME_VAR to get into the environment

export SOME_VAR

# write all environment variables to the output
env

test.d:
import std.process:
void main()
{
    processEnv(system("./script.sh")); // need to write the processEnv  
function which processes the output from env.
}

I don't know what your real test case looks like, so I can't really  
comment on the approach.  If it's simply loading file-defined environment  
variables, there are better ways (as I'm sure you're aware).

-Steve


More information about the Digitalmars-d-learn mailing list