Prepare to be enlightened:
#!/usr/bin/perl
# setenv from within perl to effect parent shell
# actually parent should be more appropriately
# called "adopted" or "step-parent", re execl
# there is one little requirement:
# you should run this program via shell's exec:
# % exec <scriptname>
#
# author: bliako
# date: 09/07/2018
use Inline C => DATA;
# ...
# this should be the last statement in your script
# because nothing else will be executed after that
# not even the 'or die ...'
mysetenv("test", "TURE") or die "mysetenv() failed";
__END__
__C__
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int mysetenv(const char *K, const char *V){
if( K==NULL || V==NULL ){ return 0; }
char *shell = getenv("SHELL");
if( setenv(K, V, 1) ){
fprintf(stderr, "mysetenv() : call to setenv() has fai
+led.\n");
return 1;
}
// replace caller shell with a new shell which now has
// set this new env var
//printf("shell to exec is %s\n", shell);
execl(shell, NULL, NULL);
perror("execl failed, ");
return 1;
}
% echo $test
% exec env.pl
% echo $test
TURE
The above script sets the specified environment variable and at the same time replaces
current program (the perl script) with a new shell which inherits the env. If this script is
executed via shell's exec, e.g. % exec env.pl the current shell will be replaced by the new shell created in the perl script and having the set environment.
For more flexibility, the mysetenv() function should be split into 2 parts. The setenv part and the execl part. The execl part should be executed last. After execl call the perl script process stops to exist!
bw, bliako (and excuse my boasting)
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.