1

If I execute following command in bash (debian 10):

comm -1 -3  <(sort $file1) <(sort $file2) > $output_file

I got the expected result.

But if I try that inside a perl script:

`comm -1 -3  <(sort $file1) <(sort $file2) > $output_file`;

I got following:

sh: 1: Syntax error: "(" unexpected

How could I make it work in perl?

4
  • 1
    Just a guess, but is there a chance Perl's using a different shell? You may find this answer How can I call a shell command in my Perl script? helpful. Commented Aug 2, 2022 at 19:17
  • 1
    @radical7 It uses /bin/sh or cmd. Some people expect $ENV{SHELL} to be used, but that makes no sense. Program-provided commands must necessarily target a specific shell, so it makes no sense to use the user's preferred shell. The env var should only be used when creating an interactive shell for the user. Commented Aug 2, 2022 at 19:33
  • @ikegami so in a sense, I was right ;-) Commented Aug 2, 2022 at 22:03
  • @radical7 You were 100% correct. I was confirming with details. Commented Aug 2, 2022 at 22:12

1 Answer 1

1

Backticks use /bin/sh (or cmd), not bash, so you'll need to construct a POSIX shell command. That command could, of course, invoke bash.

The following achieves that, while also fixing code injection bugs:

use String::ShellQuote qw( shell_quote );

my $sort_cmd1 = shell_quote( "sort", "--", $file1 ) . ' 2>&1';
my $sort_cmd2 = shell_quote( "sort", "--", $file2 ) . ' 2>&1';
my $bash_cmd  = shell_quote( "comm", "-1", "-3" ) . " <( $sort_cmd1 ) <( $sort_cmd2 )";
my $sh_cmd    = shell_quote( "bash", "-c", $bash_cmd );

my $output = `$sh_cmd`;

or

use String::ShellQuote qw( shell_quote );

my $bash_cmd = 'comm -1 -3 <( sort -- "$1" 2>&1 ) <( sort -- "$2" 2>&1 )';
my $sh_cmd = shell_quote( "bash", "-c", $bash_cmd, "dummy", $file1, $file2 );

my $output = `$sh_cmd`;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.