1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
#!/usr/bin/env perl
## envstore - save and load environment variables
## Copyright © 2009 by Daniel Friesel <derf@derf.homelinux.org>
## License: WTFPL <http://sam.zoy.org/wtfpl>
use strict;
use warnings;
my $store_file = "/tmp/.envstore-$>";
my %store;
my $action = shift;
my $arg = shift;
my ($key, $value);
sub check_store {
my ($mode, $uid);
unless (-e $store_file) {
return(0);
}
($mode, $uid) = (stat($store_file))[2,4];
$mode &= 0x00077;
if ($uid != $<) {
print STDERR "envstore: store file not owned by us\n";
exit(1);
}
if ($mode > 0) {
print STDERR "envstore: store file writable by group/others\n";
printf("%o", $mode);
exit(1);
}
return(1);
}
sub load_store {
my ($key, $value);
return unless check_store;
open(my $handle, '<', $store_file) or die("Cannot read $store_file: $!");
while (<$handle>) {
chomp;
/^(\S+)\s+(.*)$/ or next;
($key, $value) = ($1, $2);
$store{$key} = $value;
}
close($handle);
}
sub save_store {
my $key;
umask(0077);
open(my $handle, '>', $store_file) or die("Cannot open $store_file: $!");
foreach $key (keys(%store)) {
print $handle "$key\t$store{$key}\n";
}
close($handle);
}
sub get_keyvalue {
my $arg = shift;
my ($key, $value);
$arg =~ /^(\w+)(?:=(.*))?$/;
($key, $value) = ($1, $2);
unless (defined($2)) {
if (exists($ENV{$key})) {
$value = $ENV{$key};
} else {
print STDERR "No such parameter: $key";
exit(1);
}
}
return($key, $value);
}
load_store;
if ($action eq 'save') {
($key, $value) = get_keyvalue($arg);
$store{$key} = $value;
save_store;
} elsif ($action eq 'eval') {
while (($key, $value) = each(%store)) {
$value =~ s/'/'"'"'/g;
print "export $key='$value'\n";
}
} elsif ($action eq 'show') {
while (($key, $value) = each(%store)) {
printf("%-15s = %s\n", $key, $value);
}
} elsif ($action eq 'rm') {
delete($store{$arg});
save_store;
} elsif ($action eq 'clear') {
unlink($store_file);
} else {
print STDERR "Usage: envstore <save|eval|show|rm|clear> [args]\n";
exit(1);
}
|