Reputation: 385
I need some quick advice on perl script. I created a script that basically calls other perl scripts and many other shell scripts within those. The problem I'm facing, is simply trying to make this run on a universal level by setting one environment variable.
This is on linux RHEL/CentOS by the way...
so I add my variables to .bash_profile and it works without an issue if I MANUALLY source the file first, then run my perl script! This is, OK, but I would like the script to automate this part instead of needing the extra, manual sourcing step.
So my script looks like this... in short
#!/usr/bin/perl
use warnings;
use strict;
`/bin/bash ~/.bash_profile`;
blah blah blah more code etc;
When launching the main script (where this part of the code is) it works no problem. It's all the subsequent calls made to other scripts that are failing...as if it is not passing the variable on to the rest of the scripts.
Any ideas??
Thanks,
Upvotes: 2
Views: 5107
Reputation: 118645
Backticks (and system
, and open
, etc.) spawns a separate process that inherits the environment from your Perl program, but can only affect its own environment, not propogate changes back to your Perl script.
Shell::GetEnv
has a few tricks that will help you incorporate those changes to the child environment, but often times you will find it is easier to parse .bash_profile
yourself.
The more recent Env::Modify
module can handle this task, leveraging the tricks in Shell::GetEnv
.
use Env::Modify 'source';
source("$ENV{HOME}/.bash_profile");
Upvotes: 1
Reputation: 481
using $ENV we can get any value from .profile/.bash_profile Example: suppose any variable is store in your .profile/.bash_profile
export CONNECT="Connection"
Retrieve the same variable in your perl scripts from .profile/.bash_profile as:
my $DB_CONNECT = $ENV{CONNECT};
Upvotes: 0
Reputation: 386361
Environment variables are inherited by child processes from their parent, so you simply need to launch perl
from a shell that sourced ~/.bash_profile
.
bash
login shells source that file automatically, so it's just a question of setting bash
as your login shell. You could also use bash -l
.
bash -lc 'exec script.pl args'
If you can't setup the correct environment before launching Perl, you can bootstrap a bash login shell.
if (@ARGV && $ARGV[0] eq 'setup') {
shift(@ARGV);
} else {
exec('bash', '-lc', 'exec "$@"', '-', $^X, $0, 'setup', @ARGV) or die $!;
}
In all three cases, the variable is accessed using
$ENV{VAR_NAME}
Upvotes: 1
Reputation: 123461
$ENV{"name"}=...
. These variables then will be propagated automatically to any programs started from within the perl script, no matter if perl or shell scripts$ENV
. This is error prone because there might be several ways to declare the variables.env
afterwards. Then you read and parse the output from this shell. This is similar to the previous proposal, but the output you have to parse is more clearly defined.Upvotes: 7