can we source a shell script in perl script

前端 未结 7 753
隐瞒了意图╮
隐瞒了意图╮ 2021-01-15 04:54

can we source a shell script in the perl script??

Example: Program 1:

cat test1.sh
#!/bin/ksh
DATE=/bin/date

program 2:

<         


        
7条回答
  •  北海茫月
    2021-01-15 05:30

    I don't know that this will help, but I felt compelled to come up with a way to write this in Perl. My intent was to have Perl run a shell script, and to assign any shell variables it sets to like-named variables in the Perl script.

    The others are correct in that any shell script you "source" is going to be in a sub-shell. I figured I could use "sh -x cmd" to at least have the shell show the variables as they're set.

    Here's what I wrote:

    use strict;  use warnings;
    
    our $DATE;
    
    my $sh_script = "./test1.sh";
    
    my $fh;
    open($fh, "sh -x '$sh_script' 2>&1 1>/dev/null |") or die "open: $!";
    foreach my $line (<$fh>) {
        my ($name, $val);
        if ($line =~ /^\+ (\w+)='(.+)'$/) {  # Parse "+ DATE='/bin/date;'
            $name = $1;
            ($val = $2) =~ s{'\\''}{'}g;  # handle escaped single-quotes (eg. "+ VAR='one'\''two'")
        } elsif ($line =~ /^\+ (\w+)=(\S+)$/) {  # Parse "+ DATE=/bin/date"
            $name = $1;
            $val = $2;
        } else {
            next;
        }
        print "Setting '$name' to '$val'\n" if (1);
        # NOTE: It'd be better to use something like "$shell_vars{$name} = $val",
        #  but this does what was asked (ie. $DATE = "/bin/date")...
        no strict 'refs';
        ${$name} = $val;    # assign to like-named variable in Perl
    }
    close($fh) or die "close: ", $! ? $! : "Exit status $?";
    
    print "DATE: ", `$DATE` if defined($DATE);
    

    There's certainly more error-checking you could do, but this did the trick for me if all you want to catch is shell variables.

提交回复
热议问题