in reply to setenv in perl
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)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: YES you can! Re: setenv in perl
by bliako (Abbot) on Jul 09, 2018 at 13:56 UTC | |
|
Re: NO you can't ! Re: setenv in perl
by KurtZ (Friar) on Jul 09, 2018 at 16:42 UTC | |
by bliako (Abbot) on Jul 09, 2018 at 20:46 UTC | |
by KurtZ (Friar) on Jul 10, 2018 at 00:58 UTC | |
by bliako (Abbot) on Jul 09, 2018 at 17:26 UTC | |
by LanX (Saint) on Jul 09, 2018 at 18:01 UTC | |
by bliako (Abbot) on Jul 09, 2018 at 18:22 UTC | |
|
Re: YES you can! Re: setenv in perl
by Anonymous Monk on Jul 09, 2018 at 14:12 UTC | |
|
Re: YES you can! Re: setenv in perl
by Aldebaran (Curate) on Jul 11, 2018 at 16:58 UTC | |
by bliako (Abbot) on Jul 12, 2018 at 12:10 UTC |