This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
oops, backout bogus change#3545
[perl5.git] / 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,$command,$args,$vars) = '';
30    local(*dotsh);
31    undef *dotsh;
32    $dotsh = shift(@sh);
33    @dotsh = split (/\s/, $dotsh);
34    $command = shift (@dotsh);
35    $args = join (" ", @dotsh);
36    $vars = join ("\n", @sh);
37    open (_SH_ENV, "$command") || die "Could not open $dotsh!\n";
38    chop($_ = <_SH_ENV>);
39    $shell = "$1 -c" if ($_ =~ /^\#\!\s*(\S+(\/sh|\/ksh|\/zsh|\/csh))\s*$/);
40    close (_SH_ENV);
41    if (!$shell) {
42       if ($ENV{'SHELL'} =~ /\/sh$|\/ksh$|\/zsh$|\/bash$|\/csh$/) {
43          $shell = "$ENV{'SHELL'} -c";
44       } else {
45          print "SHELL not recognized!\nUsing /bin/sh...\n";
46          $shell = "/bin/sh -c";
47       }
48    }
49    if (length($vars) > 0) {
50       system "$shell \"$vars;. $command $args; set > /tmp/_sh_env$$\"";
51    } else {
52       system "$shell \". $command $args; set > /tmp/_sh_env$$\"";
53    }
54
55    open (_SH_ENV, "/tmp/_sh_env$$") || die "Could not open /tmp/_sh_env$$!\n";
56    while (<_SH_ENV>) {
57        chop;
58        m/^([^=]*)=(.*)/s;
59        $ENV{$1} = $2;
60    }
61    close (_SH_ENV);
62    system "rm -f /tmp/_sh_env$$";
63
64    foreach $key (keys(%ENV)) {
65        $tmp .= "\$$key = \$ENV{'$key'};" if $key =~ /^[A-Za-z]\w*$/;
66    }
67    eval $tmp;
68 }
69 1;