Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an environment variable through a Perl script [duplicate]

Tags:

linux

bash

sh

perl

I am trying to set an environment variable, LD_LIBRARY_PATH, through a Perl script in the following way:

I have created .profile under /root

.profile has an export command say:

export LD_LIBRARY_PATH=/

My Perl script is test.pl and it has:

#!/usr/bin/perl
system(". /root/.profile");

When I execute ./test.pl, LD_LIBRARY_PATH doesn't change.

What am I doing wrong?

like image 540
user2848437 Avatar asked Oct 05 '13 00:10

user2848437


1 Answers

Your current script doesn't even change an environment variable in the Perl script itself. Rather, it invokes a shell as a subprocess; that shell process executes . /root/.profile, which updates $LD_LIBRARY_PATH only in that shell process.

You can change an environment variable in a Perl script (more precisely, in the process running the Perl script) by updating %ENV:

$ENV{LD_LIBRARY_PATH} = '/'; # or some more reasonable value

As perldoc -v %ENV says:

%ENV The hash %ENV contains your current environment. Setting a value in "ENV" changes the environment for any child processes you subsequently "fork()" off.

But that probably still won't do what you want; it won't (and can't) affect the environment of the process that invokes the Perl script (your interactive shell), only the Perl process itself and anything it invokes.

I'll assume you want to update $LD_LIBRARY_PATH in your current interactive shell process. To do that, you can have you Perl script print a shell command that will update $LD_LIBRARY_PATH. Then, rather than simply running your Perl script, you can execute it and then evaluate its output. For example:

$ cat env.pl
#!/usr/bin/perl

use strict;
use warnings;

print "export LD_LIBRARY_PATH=/\n";
$ ./env.pl          # just prints the command without executing it
export LD_LIBRARY_PATH=/
$ eval $(./env.pl)  # executes the command in the current shell
$ echo $LD_LIBRARY_PATH 
/
$ 

This assumes that your current shell is bash or something similar.

Another option: After modifying %ENV, your Perl script can invoke another command, even a new interactive shell. The new process will inherit its environment from the Perl script. This can be a bit cumbersome, though; for example, if the new process is an interactive shell, it won't inherit unexported variables or history from the parent shell.

(One note, not directly related to your question: The fact that you're messing with /root/.profile implies that you're doing things as root (superuser). This can be dangerous. Use the root account (either by logging into it or via sudo only for things that actually need root privileges. For anything else, use a personal user account.

like image 134
Keith Thompson Avatar answered Oct 26 '22 11:10

Keith Thompson