Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Loading Environment Variables from a File.

by Abigail-II (Bishop)
on Jul 13, 2003 at 22:39 UTC ( #273841=snippet: print w/ replies, xml ) Need Help??

Description: An often asked question is how to "source" a file, like you do in the shell, to set one or more environment variables. The easy answer is: first source the file, then start the program. But what if the file to source isn't known in advance? Or it's impossible to write a wrapper script? Put the code below at or near the beginning of your program.

The code below runs in combination with the Korn shell, and probably any other Bourne shell decendent, including the POSIX shell. I don't know whether this works in the standard Windows shell - probably not due to quoting issues.

Abigail

    my $ENVIRONMENT = "/some/file/with/environment/variables/";
    
    if (@ARGV && $ARGV [0] eq '--sourced_environment') {
        shift;
    }
    else {
        if (-f $ENVIRONMENT) {
            # 
            # Now we perform a double exec. The first exec gives us a 
+shell, 
            # allowing us the source the file with the environment var
+iables.
            # Then, from within the shell we re-exec ourself - but wit
+h an
            # argument that will prevent us from going into infinite r
+ecursion.
            # 
            # We cannot do a 'system "source $ENVIRONMENT"', because 
            # environment variables are not propagated to the parent.
            #
            # Note the required trickery to do the appropriate shell q
+uoting
            # when passing @ARGV back to ourselves.
            #
            # Also note that the program shouldn't normally be called 
+with
            # '--sourced_environment' - if so, pick something else.
            #

            @ARGV = map {s/'/'"'"'/g; "'$_'"} @ARGV;

            exec << "        --";
                source '$ENVIRONMENT'
                exec    $0  --sourced_environment @ARGV;
            --
            die  "This should never happen.";
        }
    }
Comment on Loading Environment Variables from a File.
Download Code

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://273841]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (11)
As of 2014-12-25 06:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (159 votes), past polls