Created
September 16, 2014 14:37
-
-
Save charliek/604f83e9e5a415353eac to your computer and use it in GitHub Desktop.
Perl Environment Variable Loader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
# Take in a file containing environment variables line by line | |
# and if the variable is not yet set print out an export command | |
# that can be evaluated by bash. This allows us to specify environment | |
# values in a much easier format than otherwise allowed. For example: | |
# | |
# # Comments are expressed with a leading hash sign and on their own line. | |
# # Empty lines are ok. | |
# | |
# # Values will be trimmed so lining up spaces will work as expected. | |
# # Each non-blank, non-comment line will be split on the first white | |
# # space character and spaces after that are ok. | |
# MY_ENV_VAL -MX:400 -BD200 | |
# EVAL2 BLAH | |
# | |
# # Empty string environment values are possible by just specifying a name | |
# BLANK_ENV_VAL | |
# | |
# This file would output: | |
# export MY_ENV_VAL='-MX:400 -BD200' | |
# export EVAL2='BLAH' | |
# export BLANK_ENV_VAL='' | |
# | |
# But if any of the values were already in the environment the line would be | |
# skipped. To run this file within a docker run file you would call it like: | |
# | |
# eval $(loadEnv /my/env/file.txt) | |
# | |
use strict; | |
use warnings; | |
sub trim { | |
my $s = shift; | |
$s =~ s/^\s+|\s+$//g; | |
return $s | |
}; | |
my $num_args = $#ARGV + 1; | |
if ($num_args != 1) { | |
print "\nUsage: loadEnvFile.pl [filename]\n"; | |
exit 1; | |
} | |
my $file = $ARGV[0]; | |
open my $info, $file or die "Could not open $file: $!"; | |
my $varName; | |
my $varValue; | |
while( my $line = <$info>) { | |
$line = trim($line); | |
if ($line =~ /^\#/) { | |
next; | |
} else { | |
my @words = split /\s+/, $line, 2; | |
if (scalar @words > 0) { | |
$varName = trim($words[0]); | |
$varValue = ""; | |
if (scalar @words == 2) { | |
$varValue = trim($words[1]); | |
} | |
if (! defined $ENV{$varName}) { | |
print "export $varName='$varValue'\n"; | |
} | |
} | |
} | |
} | |
close $info; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could enhance with escaping special characters later: