Initial import from FreeBSD RELENG_4:
[dragonfly.git] / contrib / perl5 / lib / dotsh.pl
1 #
2 #   @(#)dotsh.pl                                               03/19/94
3 #
4 #   Author: Charles Collins
5 #
6 #   Description:
7 #      This routine takes a shell script and 'dots' it into the current perl
8 #      environment. This makes it possible to use existing system scripts
9 #      to alter environment variables on the fly.
10 #
11 #   Usage:
12 #      &dotsh ('ShellScript', 'DependentVariable(s)');
13 #
14 #         where
15 #
16 #      'ShellScript' is the full name of the shell script to be dotted
17 #
18 #      'DependentVariable(s)' is an optional list of shell variables in the
19 #         form VARIABLE=VALUE,VARIABLE=VALUE,... that 'ShellScript' is
20 #         dependent upon. These variables MUST be defined using shell syntax.
21 #
22 #   Example:
23 #      &dotsh ('/tmp/foo', 'arg1');
24 #      &dotsh ('/tmp/foo');
25 #      &dotsh ('/tmp/foo arg1 ... argN');
26 #
27 sub dotsh {
28    local(@sh) = @_;
29    local($tmp,$key,$shell,*dotsh,$command,$args,$vars) = '';
30    $dotsh = shift(@sh);
31    @dotsh = split (/\s/, $dotsh);
32    $command = shift (@dotsh);
33    $args = join (" ", @dotsh);
34    $vars = join ("\n", @sh);
35    open (_SH_ENV, "$command") || die "Could not open $dotsh!\n";
36    chop($_ = <_SH_ENV>);
37    $shell = "$1 -c" if ($_ =~ /^\#\!\s*(\S+(\/sh|\/ksh|\/zsh|\/csh))\s*$/);
38    close (_SH_ENV);
39    if (!$shell) {
40       if ($ENV{'SHELL'} =~ /\/sh$|\/ksh$|\/zsh$|\/csh$/) {
41          $shell = "$ENV{'SHELL'} -c";
42       } else {
43          print "SHELL not recognized!\nUsing /bin/sh...\n";
44          $shell = "/bin/sh -c";
45       }
46    }
47    if (length($vars) > 0) {
48       system "$shell \"$vars;. $command $args; set > /tmp/_sh_env$$\"";
49    } else {
50       system "$shell \". $command $args; set > /tmp/_sh_env$$\"";
51    }
52
53    open (_SH_ENV, "/tmp/_sh_env$$") || die "Could not open /tmp/_sh_env$$!\n";
54    while (<_SH_ENV>) {
55        chop;
56        m/^([^=]*)=(.*)/s;
57        $ENV{$1} = $2;
58    }
59    close (_SH_ENV);
60    system "rm -f /tmp/_sh_env$$";
61
62    foreach $key (keys(%ENV)) {
63        $tmp .= "\$$key = \$ENV{'$key'};" if $key =~ /^[A-Za-z]\w*$/;
64    }
65    eval $tmp;
66 }
67 1;