Perl escaping argument for bash execution

前端 未结 5 1547
感动是毒
感动是毒 2020-12-21 11:16

I\'ve written some code in Perl which executes some bash command within its execution. My problem was when bash command attributes contained white space inside which failed

5条回答
  •  情书的邮戳
    2020-12-21 11:30

    Don't use backticks to keep your string away from the shell, and hence all the quoting issues:

    system 'echo', $var;
    

    You write:

    I need stdout from this command unfortunately. Other thing is that variables are used in a lil bit complicated command which uses many pipes and stuff: echo $var | sed | grep | awk | and so on... and so on...

    You might want to investigate with something like this (untested, largely cribbed from the IPC::Open3 perldoc)

    use IPC::Open3;
    use Symbol 'gensym';
    
    my ($wtr, $rdr, $err);
    $err = gensym;
    my $pid = open3($wtr, $rdr, $err, 'sed|grep|awk|and so on');
    print $wtr $var;
    close $wtr;
    my $output = <$rdr>;
    waitpid $pid, 0;
    

    If your pipeline is very messy, store it in a shell script file, and invoke that script from perl.

提交回复
热议问题