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)
In reply to YES you can! Re: setenv in perl
by bliako
in thread setenv in perl
by dideod.yang
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |