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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.