Search code examples
bashperlbackticks

Perl backticks using bash


In Perl, the default shell to execute backticks is sh. I'd like to switch to use bash for its richer syntax. So far I found that the suggested solution is

`bash -c \"echo a b\"`

The apparent drawback is that the escaped double quotes, which means I will have difficulty to use double quotes in my bash args. For example, if I wanted to run commands requiring double quotes in bash

echo "a'b"

The above method will be very awkward.

Perl's system() call has a solution for this problem: to use ARRAY args,

system("bash", "-c", qq(echo "a'b"));

This keeps my original bash command unmodified, and almost always.

I'd like to use ARRAY args in backticks too. Is it possible?


Solution

  • Capture::Tiny is a very nice option: as the SYNOPSIS shows, you can do

    use Capture::Tiny 'capture';
    my ($output, $error_output, $exit_code) = capture {
        system(@whatever);
    };
    

    as well as using system inside capture_stdout if you want the simpler behavior of backticks.

    Plus it's very general-purpose, working on Perl code (even Perl code that does weird stuff) as well as external programs, so it's a good thing to have in your toolbox.