如何在Perl的system()中使用bash语法?

Fra*_*ank 14 bash perl command

如何bash在Perl system()命令中使用语法?

我有一个特定于bash的命令,例如以下命令,它使用bash的进程替换:

 diff <(ls -l) <(ls -al)
Run Code Online (Sandbox Code Playgroud)

我想用Perl来调用它

 system("diff <(ls -l) <(ls -al)")
Run Code Online (Sandbox Code Playgroud)

但它给了我一个错误,因为它使用sh而不是bash执行命令:

sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: `sort <(ls)'
Run Code Online (Sandbox Code Playgroud)

vla*_*adr 46

告诉Perl直接调用bash.使用list变体system()来降低引用的复杂性:

my @args = ( "bash", "-c", "diff <(ls -l) <(ls -al)" );
system(@args);
Run Code Online (Sandbox Code Playgroud)

如果你打算经常这样做,你甚至可以定义一个子程序:

sub system_bash {
  my @args = ( "bash", "-c", shift );
  system(@args);
}

system_bash('echo $SHELL');
system_bash('diff <(ls -l) <(ls -al)');
Run Code Online (Sandbox Code Playgroud)

  • 这也可以防止你调用/ bin/sh来运行bash (3认同)

Dav*_*d Z 6

 system("bash -c 'diff <(ls -l) <(ls -al)'")
Run Code Online (Sandbox Code Playgroud)

理论上应该这样做.-c根据手册页,Bash的选项允许您传递shell命令来执行.