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)'
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.
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.
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)');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With