Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use bash syntax in Perl's system()?

Tags:

bash

command

perl

How can I use bash syntax in Perl's system() command?

I have a command that is bash-specific, e.g. the following, which uses bash's process substitution:

 diff <(ls -l) <(ls -al)

I would like to call it from Perl, using

 system("diff <(ls -l) <(ls -al)")

but it gives me an error because it's using sh instead of bash to execute the command:

sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: `sort <(ls)'
like image 576
Frank Avatar asked Feb 20 '09 21:02

Frank


People also ask

How do I run a bash script in Perl?

Note: Here, once the bash script completes execution it will continue with the execution of the perl script. Below is a perl script “perl-script.pl” which calls an external bash script “bash-script.sh”. #!/usr/bin/perl use strict; use warnings; print "Running parent perl script.

What is system command in Perl?

Perl's system command provides a way to execute a shell command on the underlying platform. For example, if you are running on a Unix platform, the command: system("ls -l") will print a long listing of files to stdout.


2 Answers

Tell Perl to invoke bash directly. Use the list variant of system() to reduce the complexity of your quoting:

my @args = ( "bash", "-c", "diff <(ls -l) <(ls -al)" );
system(@args);

You may even define a subroutine if you plan on doing this often enough:

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

system_bash('echo $SHELL');
system_bash('diff <(ls -l) <(ls -al)');
like image 176
vladr Avatar answered Sep 24 '22 04:09

vladr


 system("bash -c 'diff <(ls -l) <(ls -al)'")

should do it, in theory. Bash's -c option allows you to pass a shell command to execute, according to the man page.

like image 42
David Z Avatar answered Sep 23 '22 04:09

David Z